<?php
namespace control;
/*
*核销单类
*/

class writeOffOrderClass extends adIndexClass
{
    private const page = 'writeOffOrder';
    private const table = 'write_off_order';
    private const title = '核销单';
    /**
     * @var mixed|string
     */
    private array $typeOption = ['预收冲应收', '预付冲应付', '应收冲应付', '应付转应付', '应收转应收'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => L('writeOffOrder.home.orderNo'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type'  => [
                        'name'  => L('writeOffOrder.home.type'),
                        'width' => 200,
                    ],
                    'targetNameOne'         => [
                        'name'  => L('writeOffOrder.home.kehu'),
                        'width' => 200,
                    ],
                    'targetNameTwo'          => [
                        'name'  => L('writeOffOrder.home.supplier'),
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => L('writeOffOrder.home.money') . "(" . static::$unit . ")",
                        'width' => 200,
                    ],
                    'stid'          => [
                        'name'  => L('writeOffOrder.home.stid'),
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => L('writeOffOrder.home.createTime'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('writeOffOrder.home.state'),
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('writeOffOrder.home.orderNo') => text(array("name" => "orderNo")),
                    L('writeOffOrder.home.type')   => select(["name" => "type", 'option' => $this->typeOption]),
                    L('writeOffOrder.home.kehu') => clientProfileClass::kehuSelect(array('title' => '')),
                ],
                [
                    L('writeOffOrder.home.supplier') => supplierClass::supplierSelect(array('title' => '')),
                    L('writeOffOrder.home.stid') => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'where' => "state !='离职'", 'sqlField' => 'name', 'class' => 'width200']),
                    L('writeOffOrder.home.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    L('writeOffOrder.home.state') => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','chooseType',{})\" class='spanButton'>" . L('writeOffOrder.home.new') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('writeOffOrder.home.del') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "type" => $this->post('type'),
            "stid" => $this->post('stid'),
            'coid' => self::$coid,
        );
        $and = $this->seeSelf(self::page, 'stid');
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('writeOffOrder.home.edit'), "click" => "newIframe('" . L('writeOffOrder.home.detail') . "','" . $url . "&fun=edit&type={$array['type']}&id=" . $array['id'] . "')"),
                "detail" => array("title" => L('writeOffOrder.home.detail'), "click" => "newIframe('" . L('writeOffOrder.home.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }

            if (in_array($array['type'], ['预收冲应收', '应收冲应付', '应收转应收'])) {
                $kehu = query('kehu', "khid = '$array[targetId]'");
                $supplier = query('supplier', "id = '$array[otherId]'");
                $targetNameOne = $kehu['companyName'];
            } else {
                $supplier = query('supplier', "id = '$array[targetId]'");
                $targetNameOne = '';
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'targetNameOne':
                        $row[] = $targetNameOne;
                        break;
                    case 'targetNameTwo':
                        $targetNameTwo = $supplier['name'];
                        $row[] = $targetNameTwo;
                        break;
                    case 'money':
                        //核销金额
                        switch ($array['type']) {
                            case '预收冲应收':
                                $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$array[id]' and classify = '预收'", 'sum' => "money"));
                                break;
                            case '预付冲应付':
                                $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$array[id]' and classify = '预付'", 'sum' => "money"));
                                break;
                            case '应收转应收':
                            case '应收冲应付':
                                $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$array[id]' and classify = '应收'", 'sum' => "money"));
                                break;
                            case '应付转应付':
                                $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$array[id]' and classify = '应付'", 'sum' => "money"));
                                break;
                            default:
                                $money = 0;
                                break;
                        }
                        $row[] = $money;
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . "_detail",
            'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $totalQuery,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        $newOrderWord = L('writeOffOrder.home.newOrder');
        $json['html'] .= <<<efo
        <script>
        function chooseType(){
            let type = $("form[name='writeOffOrderChooseTypeForm'] [name='type']:checked").val();
            $('#writeOffOrderChooseType').hide();
            newIframe('{$newOrderWord}',root+'control/adIndex.html?cla=writeOffOrder&fun=edit&type='+type)
        }
        </script>
efo;

        return json_encode($json, 320);
    }

    /**
     * 选择订单类型
     * @return bool|string
     */
    public function chooseType(): bool|string
    {
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('writeOffOrder.chooseType.type') . "：" => radio(array('name' => 'type', 'value' => $this->typeOption, 'checked' => $this->typeOption[0])),
            ),
        )
        ));
        //返回
        return $this->layer(array(
            "title" => L('writeOffOrder.chooseType.choiceType'),
            "height" => 151,
            "html" => $html,
            'button' => "<input onclick=\"chooseType()\" type='button' class='button' value='" . L('writeOffOrder.chooseType.sub') . "'>"
        ));
    }


    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $offType = $this->get('type');
        if (empty($offType) || !in_array($offType, $this->typeOption)) {
            $data['html'] = L('writeOffOrder.edit.empty');
        } else {
            $button[] = [
                "name" => '保存为草稿',
                "type" => "点击事件",
                "title" => '保存为草稿',
                'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
            ];
            $button[] = [
                'style' => 'li-btn-blue-bg',
                "name" => "保存并提交",
                "type" => "点击事件",
                "title" => "保存",
                'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
            ];
            $inReceipt = new inReceiptClass();
            $lineTwo = [];
            $tableTitleOne = $tableTitleTwo = [];
            $tableOne = $tableTwo = [];
            $tr[] = ['', L('writeOffOrder.edit.sOrderNo'), L('writeOffOrder.edit.type'), L('writeOffOrder.edit.recordDate'), L('writeOffOrder.edit.totalMoney') . '(' . static::$unit . ')', L('writeOffOrder.edit.checkMoney') . '(' . static::$unit . ')', L('writeOffOrder.edit.notWrittenOff') . '(' . static::$unit . ')', L('writeOffOrder.edit.thisMoney') . '(' . static::$unit . ')'];
            $sourceTr[] = ['', L('writeOffOrder.edit.sOrderNo'), L('writeOffOrder.edit.type'), L('writeOffOrder.edit.recordDate'), L('writeOffOrder.edit.settlementType'), L('writeOffOrder.edit.period'), L('writeOffOrder.edit.totalMoney') . '(' . static::$unit . ')', L('writeOffOrder.edit.checkMoney') . '(' . static::$unit . ')', L('writeOffOrder.edit.notWrittenOff') . '(' . static::$unit . ')', L('writeOffOrder.edit.thisMoney') . '(' . static::$unit . ')'];
            $addPreOrderWord = L('writeOffOrder.edit.addPreOrder');
            $checkMoneyTotalWord = L('writeOffOrder.edit.checkMoneyTotal');
            switch ($offType) {
                case '预收冲应收':
                    $titleOne = '预收单据';
                    $titleTwo = '应收单据';
                    $lineOne = [
                        must . L('writeOffOrder.edit.type') => $offType . hidden(array('name' => 'type', 'value' => $offType)),
                        must . L('writeOffOrder.edit.kehu') . "：" => clientProfileClass::kehuSelect(array("name" => "targetId", "value" => $info['targetId'])),
                        must . L('writeOffOrder.edit.recordDate') . "：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    ];
                    $lineTwo = [
                        L('writeOffOrder.edit.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                    ];
                    /******预收*****/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '预收' order by list"));
                    foreach ($result['array'] as $k=>$array) {
                        $mx = query('receipt', "id = '$array[sourceId]'");
                        $orderType = '';
                        if ($mx['classify'] == 1) {
                            $orderType = L('writeOffOrder.edit.receipt');
                        } elseif ($mx['classify'] == 0) {
                            $orderType = L('writeOffOrder.edit.payment');
                        }
                        //单据金额
                        $totalMoney = find(array('table' => 'receipt_detail', "where" => "orderId = '$mx[id]'", 'sum' => "money"));
                        //已核销金额
                        $checkMoney = find(array('table' => 'receipt_source', "where" => "orderId = '$mx[id]'", 'sum' => "money"));
                        //核销单(从收款单中找)
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $tr[] = [
                            componentClass::tablePperation($k+1,"delTableRow(this)").
                            hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                            hidden(array('name' => 'mxSourceId[]', 'value' => $array['sourceId'])),
                            $mx['orderNo'],
                            $orderType,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            text(array('name' => 'mxMoney[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['money'])),
                        ];
                    }
                    /******应收*****/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收' order by list"));
                    foreach ($result['array'] as $k=>$array) {
                        $settlementType = '';
                        $period = '';
                        if ($array['sourceTable'] == 'sale_send_order') {
                            $type = '销售发货单';
                            $mx = query('sale_send_order', "id = '$array[sourceId]'");
                            $settlementType = $mx['settlementType'];
                            $period = $inReceipt->settlementPeriod($mx['settlementType'], $mx['recordDate'], $mx['settlementDay']);
                            //单据金额
                            $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        } else {
                            $type = '销售退货单';
                            $mx = query('sale_refund_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        }

                        if ($mx['khid'] != $info['targetId']) {
                            //转过的单子
                            $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$mx[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                        }
                        $totalMoney = $type == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $sourceTr[] = [
                            componentClass::tablePperation($k+1,"delTableRow(this)").
                            hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                            hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            $settlementType,
                            $period,
                            $totalMoney,
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            text(array('name' => 'checkMoney[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['money'])),
                        ];
                    }
                    $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '预收'", 'sum' => "money"));
                    $total_tr = [
                        7 => "<span id='checkMoneyTotal'>".$money."</span>",
                    ];
                    $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr));
                    $tableOne = $this->editList([
                        'title' => $titleOne,
                        'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addPreOrder',$('form[name=writeOffOrderEditForm]').serialize())\">{$addPreOrderWord}</span>",
                        'html' => "<div id='table_one'>
                                {$list}
                            </div>",
                    ]);
                    $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收'", 'sum' => "money"));
                    $total_tr = [
                        9 => "<span id='checkMoneyTotalTwo'>".$money."</span>",
                    ];
                    $list = $this->listTable(array('tr' => $sourceTr, 'end' => true, 'total' => $total_tr));
                    $tableTwo = $this->editList([
                        'title' => $titleTwo,
                        'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addRecOrder',$('form[name=writeOffOrderEditForm]').serialize())\">{$addPreOrderWord}</span>",
                        'html' => "<div id='materialTable'>
                                {$list}
                            </div>",
                    ]);
                    break;
                case '预付冲应付':
                    $titleOne = '预付单据';
                    $titleTwo = '应付单据';
                    $lineOne = [
                        must . L('writeOffOrder.edit.type') => $offType . hidden(array('name' => 'type', 'value' => $offType)),
                        must . L('writeOffOrder.edit.supplier') . "：" => supplierClass::supplierSelect(array('title' => L('writeOffOrder.edit.choice'),"value" => $info['targetId'],"name" => "targetId",'param'=>"{type:'启用'}")),
                            //selectMultiple(["name" => "targetId", "value" => $info['targetId'], 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'table' => "supplier", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('writeOffOrder.edit.choice')]),
                        must . L('writeOffOrder.edit.recordDate') . "：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    ];
                    $lineTwo = [
                        L('writeOffOrder.edit.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                    ];
                    /******预付*****/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '预付' order by list"));
                    foreach ($result['array'] as $k=>$array) {
                        $mx = query('receipt', "id = '$array[sourceId]'");
                        $orderType = '';
                        if ($mx['classify'] == 1) {
                            $orderType = L('writeOffOrder.edit.receipt');
                        } elseif ($mx['classify'] == 0) {
                            $orderType = L('writeOffOrder.edit.payment');
                        }
                        //单据金额
                        $totalMoney = find(array('table' => 'receipt_detail', "where" => "orderId = '$mx[id]'", 'sum' => "money"));
                        //已核销金额
                        $checkMoney = find(array('table' => 'receipt_source', "where" => "orderId = '$mx[id]'", 'sum' => "money"));
                        //核销单(从收款单中找)
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $tr[] = [
                            componentClass::tablePperation($k+1,"delTableRow(this)").
                            hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                            hidden(array('name' => 'mxSourceId[]', 'value' => $array['sourceId'])),
                            $mx['orderNo'],
                            $orderType,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            text(array('name' => 'mxMoney[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['money'])),
                        ];
                    }
                    /******应付*****/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付' order by list"));
                    foreach ($result['array'] as $k=>$array) {
                        $settlementType = '';
                        $period = '';
                        if ($array['sourceTable'] == 'purchase_get_order') {
                            $type = '采购收货单';
                            $mx = query('purchase_get_order', "id = '$array[sourceId]'");
                            $settlementType = $mx['settlementType'];
                            $period = $inReceipt->settlementPeriod($mx['settlementType'], $mx['recordDate'], $mx['settlementDay']);
                            //单据金额
                            $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        } else {
                            $type = '采购退货单';
                            $mx = query('purchase_refund_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        }
                        if ($mx['supplierId'] != $info['targetId']) {
                            //转过的单子
                            $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$mx[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                        }
                        $totalMoney = $type == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $sourceTr[] = [
                            componentClass::tablePperation($k+1,"delTableRow(this)").
                            hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                            hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            $settlementType,
                            $period,
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            text(array('name' => 'checkMoney[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['money'])),
                        ];
                    }
                    $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '预付'", 'sum' => "money"));
                    $total_tr = [
                        7 => "<span id='checkMoneyTotal'>".$money."</span>",
                    ];
                    $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr));
                    $tableOne = $this->editList([
                        'title' => $titleOne,
                        'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addPayOrder',$('form[name=writeOffOrderEditForm]').serialize())\">{$addPreOrderWord}</span>",
                        'html' => "<div id='table_one'>
                                {$list}
                            </div>",
                    ]);
                    $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付'", 'sum' => "money"));
                    $total_tr = [
                        9 => "<span id='checkMoneyTotalTwo'>".$money."</span>",
                    ];
                    $list = $this->listTable(array('tr' => $sourceTr, 'end' => true, 'total' => $total_tr));
                    $tableTwo = $this->editList([
                        'title' => $titleTwo,
                        'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addBuyOrder',$('form[name=writeOffOrderEditForm]').serialize())\">{$addPreOrderWord}</span>",
                        'html' => "<div id='materialTable'>
                                {$list}
                            </div>",
                    ]);
                    break;
                case '应收冲应付':
                    $titleOne = '应收单据';
                    $titleTwo = '应付单据';
                    $lineOne = [
                        must . L('writeOffOrder.edit.type') => $offType . hidden(array('name' => 'type', 'value' => $offType)),
                        must . L('writeOffOrder.edit.kehu') . "：" => clientProfileClass::kehuSelect(array("name" => "targetId", "value" => $info['targetId'])),
                        must . L('writeOffOrder.edit.supplier') . "：" => supplierClass::supplierSelect(array('title' => L('writeOffOrder.edit.choice'),"value" => $info['otherId'],"name" => "otherId",'param'=>"{type:'启用'}")),
                            //selectMultiple(["name" => "otherId", "value" => $info['otherId'], 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'table' => "supplier", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('writeOffOrder.edit.choice')]),
                        must . L('writeOffOrder.edit.recordDate') . "：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    ];
                    $lineTwo = [
                        L('writeOffOrder.edit.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                    ];
                    /******应收*****/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收' order by list"));
                    foreach ($result['array'] as $k=>$array) {
                        $settlementType = '';
                        $period = '';
                        if ($array['sourceTable'] == 'sale_send_order') {
                            $type = '销售发货单';
                            $mx = query('sale_send_order', "id = '$array[sourceId]'");
                            $settlementType = $mx['settlementType'];
                            $period = $inReceipt->settlementPeriod($mx['settlementType'], $mx['recordDate'], $mx['settlementDay']);
                            //单据金额
                            $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        } else {
                            $type = '销售退货单';
                            $mx = query('sale_refund_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        }
                        if ($mx['khid'] != $info['targetId']) {
                            //转过的单子
                            $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$mx[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                        }
                        $totalMoney = $type == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $sourceTr[] = [
                            componentClass::tablePperation($k+1,"delTableRow(this)").
                            hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                            hidden(array('name' => 'mxSourceId[]', 'value' => $array['sourceId'])),
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            $settlementType,
                            $period,
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            text(array('name' => 'mxMoney[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['money'])),
                        ];
                    }
                    /******应付*****/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付' order by list"));
                    foreach ($result['array'] as $k=>$array) {
                        if ($array['sourceTable'] == 'purchase_get_order') {
                            $type = '采购收货单';
                            $mx = query('purchase_get_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        } else {
                            $type = '采购退货单';
                            $mx = query('purchase_refund_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        }
                        if ($mx['supplierId'] != $info['otherId']) {
                            //转过的单子
                            $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$mx[id]' and targetIn = '$info[otherId]'", 'sum' => "money"));
                        }
                        $totalMoney = $type == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $tr[] = [
                            componentClass::tablePperation($k+1,"delTableRow(this)").
                            hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                            hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            text(array('name' => 'checkMoney[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['money'])),
                        ];
                    }

                    $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付'", 'sum' => "money"));
                    $total_tr = [
                        7 => "<span id='checkMoneyTotal'>".$money."</span>",
                    ];
                    $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr));
                    $tableOne = $this->editList([
                        'title' => $titleOne,
                        'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addRecOrder',$('form[name=writeOffOrderEditForm]').serialize())\">{$addPreOrderWord}</span>",
                        'html' => "<div id='table_one'>
                                {$list}
                            </div>",
                    ]);
                    $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收'", 'sum' => "money"));
                    $total_tr = [
                        9 => "<span id='checkMoneyTotalTwo'>".$money."</span>",
                    ];
                    $list = $this->listTable(array('tr' => $sourceTr, 'end' => true, 'total' => $total_tr));
                    $tableTwo = $this->editList([
                        'title' => $titleTwo,
                        'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addBuyOrder',$('form[name=writeOffOrderEditForm]').serialize())\">{$addPreOrderWord}</span>",
                        'html' => "<div id='materialTable'>
                                {$list}
                            </div>",
                    ]);
                    break;
                case '应收转应收':
                    $titleOne = '应收单据';
                    $lineOne = [
                        must . L('writeOffOrder.edit.type') => $offType . hidden(array('name' => 'type', 'value' => $offType)),
                        must . L('writeOffOrder.edit.manager') . "：" => clientProfileClass::kehuSelect(array("name" => "targetId", "value" => $info['targetId'])),
                        must . L('writeOffOrder.edit.rollInClient') . "：" => clientProfileClass::kehuSelect(array("name" => "otherId", "value" => $info['otherId'])),
                        must . L('writeOffOrder.edit.recordDate') . "：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    ];
                    $lineTwo = [
                        L('writeOffOrder.edit.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                    ];
                    /******应收*****/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收' order by list"));
                    foreach ($result['array'] as $k=>$array) {
                        if ($array['sourceTable'] == 'sale_send_order') {
                            $type = '销售发货单';
                            $mx = query('sale_send_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        } else {
                            $type = '销售退货单';
                            $mx = query('sale_refund_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        }
                        $totalMoney = $type == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $tr[] = [
                            componentClass::tablePperation($k+1,"delTableRow(this)").
                            hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                            hidden(array('name' => 'mxSourceId[]', 'value' => $array['sourceId'])),
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            text(array('name' => 'mxMoney[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['money'])),
                        ];
                    }

                    $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收'", 'sum' => "money"));
                    $total_tr = [
                        7 => "<span id='checkMoneyTotal'>".$money."</span>",
                    ];
                    $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr));
                    $tableOne = $this->editList([
                        'title' => $titleOne,
                        'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addShouldRec',$('form[name=writeOffOrderEditForm]').serialize())\">{$addPreOrderWord}</span>",
                        'html' => "<div id='table_one'>
                                {$list}
                            </div>",
                    ]);
                    break;
                case '应付转应付':
                    $titleOne = '应付单据';
                    $lineOne = [
                        must . L('writeOffOrder.edit.type') => $offType . hidden(array('name' => 'type', 'value' => $offType)),
                        must . L('writeOffOrder.edit.rollOutSupplier') . "：" =>
                            supplierClass::supplierSelect(array('title' => L('writeOffOrder.edit.choice'),"value" => $info['targetId'],"name" => "targetId",'param'=>"{type:'启用'}")),
                        // selectMultiple(["name" => "targetId", "value" => $info['targetId'], 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'table' => "supplier", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '请选择']),
                        must . L('writeOffOrder.edit.rollInSupplier') . "：" =>
                            supplierClass::supplierSelect(array('title' => L('writeOffOrder.edit.choice'),"value" => $info['otherId'],"name" => "otherId",'param'=>"{type:'启用'}")),
                        //selectMultiple(["name" => "otherId", "value" => $info['otherId'], 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'table' => "supplier", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('writeOffOrder.edit.choice')]),
                        must . L('writeOffOrder.edit.recordDate') . "：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    ];
                    $lineTwo = [
                        L('writeOffOrder.edit.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                    ];
                    /******应付*****/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付' order by list"));
                    foreach ($result['array'] as $k=>$array) {
                        if ($array['sourceTable'] == 'purchase_get_order') {
                            $type = '采购收货单';
                            $mx = query('purchase_get_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        } else {
                            $type = '采购退货单';
                            $mx = query('purchase_refund_order', "id = '$array[sourceId]'");
                            //单据金额
                            $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$mx[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                        }
                        $totalMoney = $type == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $tr[] = [
                            componentClass::tablePperation($k+1,"delTableRow(this)").
                            hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                            hidden(array('name' => 'mxSourceId[]', 'value' => $array['sourceId'])),
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            text(array('name' => 'mxMoney[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['money'])),
                        ];
                    }

                    $money = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付'", 'sum' => "money"));
                    $total_tr = [
                        7 => "<span id='checkMoneyTotal'>".$money."</span>",
                    ];
                    $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr));
                    $tableOne = $this->editList([
                        'title' => $titleOne,
                        'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addShouldPay',$('form[name=writeOffOrderEditForm]').serialize())\">{$addPreOrderWord}</span>",
                        'html' => "<div id='table_one'>
                                {$list}
                            </div>",
                    ]);
                    break;
                default:
                    $lineOne = [];
                    break;
            }
            //表单
            $data['button'] = $this->tableShowButton($button);
            $body = $this->edit4([
                '基本信息' => [
                    $lineOne,
                    $lineTwo,
                ]
            ]);
            $body .= $tableOne.$tableTwo;

            $data['html'] = $this->pageEdit([
                "html" => $body,
                'hidden' => hidden(['name' => 'id', 'value' => $id]),
            ]);
            $data['html'] .= <<<efo
<script>1
function addOrder(classify,secType=''){
    if (classify==='table_one'){
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addPreOrderEdit',$("form[name='addPreOrderForm']").serialize(),function (res){
              if (res.warn==2){ 
                 $('#writeOffOrderAddPreOrder').hide();
                 $("#table_one tbody").append(res.html);
                 resetNumber($("#table_one"))
                 countMoney()
               }else{
                  msg(res.warn)
              }
         },'json');
    }else if(classify==='addPayOrder'){
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addPayOrderEdit',$("form[name='addPayOrderForm']").serialize(),function (res){
              if (res.warn==2){
                  $('#writeOffOrderAddPayOrder').hide()
                  $("#table_one tbody").append(res.html);
                  resetNumber($("#table_one"))
                  countMoney()
              }else{
                  msg(res.warn)
              }
         },'json');
        
    }else if(classify==='预收冲应收' && secType==='rec'){
        //应收
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRecOrderEdit',$("form[name='addRecOrderForm']").serialize(),function (res){
              if (res.warn==2){
                  $('#writeOffOrderAddRecOrder').hide();
                  $("#materialTable tbody").append(res.html);
                  resetNumber($("#materialTable"))
                  countMoney()
              }else{
                  msg(res.warn)
              }
         },'json');
    }else if(classify==='应收冲应付' && secType==='rec'){
        //应收
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRecOrderEdit',$("form[name='addRecOrderForm']").serialize(),function (res){
              if (res.warn==2){  
                 $('#writeOffOrderAddRecOrder').hide();
                  $("#table_one tbody").append(res.html);
                  resetNumber($("#table_one"))
                  countMoney()
               }else{
                  msg(res.warn)
              }
         },'json');
    }else if((classify==='预付冲应付' || classify==='应收冲应付') && secType==='pay'){
        //应付
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addBuyOrderEdit',$("form[name='addBuyOrderForm']").serialize(),function (res){
             if (res.warn==2){   
                  $('#writeOffOrderAddBuyOrder').hide();
                  $("#materialTable tbody").append(res.html);
                  resetNumber($("#materialTable"))
                  countMoney()
               }else{
                  msg(res.warn)
              }
         },'json');
    }else if(classify==='应付转应付' && secType==='pay'){
        //应付
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addShouldPayEdit',$("form[name='addShouldPayForm']").serialize(),function (res){
              if (res.warn==2){   
                  $('#writeOffOrderAddShouldPay').hide()
                  $("#table_one tbody").append(res.html);
                  resetNumber($("#table_one"))
                  countMoney()
               }else{
                  msg(res.warn)
              }
         },'json');
    }else if(classify==='应收转应收' && secType==='rec'){
        //应收转应收
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addShouldRecEdit',$("form[name='addShouldRecForm']").serialize(),function (res){
              if (res.warn==2){   
                  $('#writeOffOrderAddShouldRec').hide()
                  $("#table_one tbody").append(res.html);
                  resetNumber($("#table_one"))
                  countMoney()
               }else{
                  msg(res.warn)
              }
         },'json');
    }
}
function countMoney(){
    let money = 0;
    $("#table_one [name='mxMoney[]']").each(function() {
        money+=Number($(this).val());
    })
    $("#checkMoneyTotal").html(money.toFixed(2));
    money = 0;
     $("#materialTable [name='checkMoney[]']").each(function() {
        money+=Number($(this).val());
    })
    $("#checkMoneyTotalTwo").html(money.toFixed(2))
}
</script>

efo;
        }

        //返回
        return $this->tab($data);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //表一
        $mxIdArr = $this->post('mxId') ?: [];
        $mxSourceIdArr = $this->post('mxSourceId') ?: [];
        $mxMoneyArr = $this->post('mxMoney') ?: [];
        //表二
        $detailIdIdArr = $this->post('detailId') ?: [];
        $sourceIdArr = $this->post('sourceId') ?: [];
        $checkMoneyArr = $this->post('checkMoney') ?: [];

        $field = [
            'targetId' => $this->post('targetId'),
            'otherId' => $this->post('otherId'),
            'text' => $this->post('text'),
            'recordDate' => $this->post('recordDate'),
            'type' => $this->post('type'),
        ];
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        $replaceIdArr = [];//用于存当前应收转应收和应付转应付表的ID;
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('writeOffOrder.editEdit.power');
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = L('writeOffOrder.editEdit.stateError');
        } else {
            //判断本次核销金额是否大于未核销金额
            $json['warn'] = $this->judgeRecMoney($field['type']);
            if ($json['warn'] === true) {
                //判断收款单或付款单
                $json['warn'] = $this->judgeReceipt($field['type']);
            }
            if ($json['warn'] === true) {
                $this->startTrans();
                $isPass = true;//事务通过标志
                if (!$info['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix' => 'HXD' . date('Ymd'),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => " and coid = '" . self::$coid . "'",
                    ], $field);
                    $field = array_merge($field, [
                        'id' => $id,
                        'orderNo' => $userNo,
                        'state' => '草稿',
                        'coid' => self::$coid,
                        'stid' => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where
                    ]);
                }
                //收付款单
                if (in_array($field['type'], ['预收冲应收', '预付冲应付'])) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx = query(self::table . "_detail", "id = '$nid'");
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'sourceTable' => 'receipt',
                                    'sourceId' => $mxSourceIdArr[$k],
                                    'classify' => $field['type'] == '预收冲应收' ? '预收' : '预付',
                                    'money' => $mxMoneyArr[$k],
                                ],
                                "where" => " id = '$nid'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'sourceTable' => 'receipt',
                                    'sourceId' => $mxSourceIdArr[$k],
                                    'classify' => $field['type'] == '预收冲应收' ? '预收' : '预付',
                                    'money' => $mxMoneyArr[$k],
                                ],
                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                if (in_array($field['type'], ['应付转应付'])) {
                    foreach ($mxIdArr as $k => $mxId) {
                        //采购收货单
                        $targetInfo = query('purchase_get_order', "id = '$mxSourceIdArr[$k]'");
                        $table = 'purchase_get_order';
                        if (empty($targetInfo['id'])) {
                            //采购退货单
                            $targetInfo = query('purchase_refund_order', "id = '$mxSourceIdArr[$k]'");
                            $table = $targetInfo['id'] ? 'purchase_refund_order' : '';
                        }
                        $mx = query(self::table . "_detail", "id = '$mxId'");
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'sourceTable' => $table,
                                    'sourceId' => $mxSourceIdArr[$k],
                                    'money' => $mxMoneyArr[$k],
                                ],
                                "where" => " id = '$mxId'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'id' => $mxId,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'classify' => '应付',
                                    'sourceTable' => $table,
                                    'sourceId' => $mxSourceIdArr[$k],
                                    'money' => $mxMoneyArr[$k],
                                ],
                            ]);
                        }

                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                        //
                        $replaceOrder = query('write_off_order_replace', "orderMxId = '$mxId' and targetOut = '$field[targetId]' and targetIn = '$field[otherId]'");
                        if (empty($replaceOrder['id'])) {
                            $replaceOrderId = self::getId();
                            $replaceIdArr[] = $replaceOrderId;
                            $warn = static::insert([
                                "table" => self::table . "_replace",
                                "field" => [
                                    'id' => $replaceOrderId,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'type' => '应付转应付',
                                    'sourceTable' => $table,
                                    'sourceId' => $mxSourceIdArr[$k],
                                    'money' => $mxMoneyArr[$k],
                                    'targetIn' => $field['otherId'],
                                    'targetOut' => $field['targetId'],
                                    'orderMxId' => $mxId,
                                ],
                            ]);
                        } else {
                            $replaceIdArr[] = $replaceOrder['id'];
                            //更新
                            $warn = static::update([
                                "table" => self::table . "_replace",
                                "field" => [
                                    'sourceTable' => $table,
                                    'sourceId' => $mxSourceIdArr[$k],
                                    'money' => $mxMoneyArr[$k],
                                    'targetIn' => $field['otherId'],
                                    'targetOut' => $field['targetId'],
                                    'orderMxId' => $mxId,
                                ],
                                "where" => " id = '$mxId'"
                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                if (in_array($field['type'], ['应收冲应付', '应收转应收'])) {
                    foreach ($mxIdArr as $k => $mxId) {
                        //销售发货单
                        $targetInfo = query('sale_send_order', "id = '$mxSourceIdArr[$k]'");
                        $table = 'sale_send_order';
                        if (empty($targetInfo['id'])) {
                            //销售退货单
                            $targetInfo = query('sale_refund_order', "id = '$mxSourceIdArr[$k]'");
                            $table = $targetInfo['id'] ? 'sale_refund_order' : '';
                        }
                        $mx = query(self::table . "_detail", "id = '$mxId'");
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'sourceTable' => $table,
                                    'sourceId' => $mxSourceIdArr[$k],
                                    'money' => $mxMoneyArr[$k],
                                ],
                                "where" => " id = '$mxId'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'id' => $mxId,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'classify' => '应收',
                                    'sourceTable' => $table,
                                    'sourceId' => $mxSourceIdArr[$k],
                                    'money' => $mxMoneyArr[$k],
                                ],
                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }

                        if ($field['type'] == '应收转应收') {
                            //
                            $replaceOrder = query('write_off_order_replace', "orderMxId = '$mxId' and targetOut = '$field[targetId]' and targetIn = '$field[otherId]'");
                            if (empty($replaceOrder['id'])) {
                                $replaceOrderId = self::getId();
                                $replaceIdArr[] = $replaceOrderId;
                                $warn = static::insert([
                                    "table" => self::table . "_replace",
                                    "field" => [
                                        'id' => $replaceOrderId,
                                        'orderId' => $id,
                                        'coid' => self::$coid,
                                        'type' => '应收转应收',
                                        'sourceTable' => $table,
                                        'sourceId' => $mxSourceIdArr[$k],
                                        'money' => $mxMoneyArr[$k],
                                        'targetIn' => $field['otherId'],
                                        'targetOut' => $field['targetId'],
                                        'orderMxId' => $mxId,
                                    ],
                                ]);
                            } else {
                                $replaceIdArr[] = $replaceOrder['id'];
                                //更新
                                $warn = static::update([
                                    "table" => self::table . "_replace",
                                    "field" => [
                                        'sourceTable' => $table,
                                        'sourceId' => $mxSourceIdArr[$k],
                                        'money' => $mxMoneyArr[$k],
                                        'targetIn' => $field['otherId'],
                                        'targetOut' => $field['targetId'],
                                        'orderMxId' => $mxId,
                                    ],
                                    "where" => " id = '$mxId'"
                                ]);
                            }
                            if (!in_array($warn, ['新增成功', '更新成功'])) {
                                $isPass = false;
                                $json['warn'] = $warn;
                                break;
                            }
                        }
                    }
                }
                if (in_array($field['type'], ['预收冲应收'])) {
                    foreach ($detailIdIdArr as $k => $mxId) {
                        //销售发货单
                        $targetInfo = query('sale_send_order', "id = '$sourceIdArr[$k]'");
                        $table = 'sale_send_order';
                        if (empty($targetInfo['id'])) {
                            //销售退货单
                            $targetInfo = query('sale_refund_order', "id = '$sourceIdArr[$k]'");
                            $table = $targetInfo['id'] ? 'sale_refund_order' : '';
                        }
                        $mx = query(self::table . "_detail", "id = '$mxId'");
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'sourceTable' => $table,
                                    'sourceId' => $sourceIdArr[$k],
                                    'money' => $checkMoneyArr[$k],
                                ],
                                "where" => " id = '$mxId'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'id' => $mxId,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'classify' => '应收',
                                    'sourceTable' => $table,
                                    'sourceId' => $sourceIdArr[$k],
                                    'money' => $checkMoneyArr[$k],
                                ],
                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                if (in_array($field['type'], ['预付冲应付', '应收冲应付'])) {
                    foreach ($detailIdIdArr as $k => $mxId) {
                        //采购收货单
                        $targetInfo = query('purchase_get_order', "id = '$sourceIdArr[$k]'");
                        $table = 'purchase_get_order';
                        if (empty($targetInfo['id'])) {
                            //采购退货单
                            $targetInfo = query('purchase_refund_order', "id = '$sourceIdArr[$k]'");
                            $table = $targetInfo['id'] ? 'purchase_refund_order' : '';
                        }
                        $mx = query(self::table . "_detail", "id = '$mxId'");
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'sourceTable' => $table,
                                    'sourceId' => $sourceIdArr[$k],
                                    'money' => $checkMoneyArr[$k],
                                ],
                                "where" => " id = '$mxId'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::table . "_detail",
                                "field" => [
                                    'id' => $mxId,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'classify' => '应付',
                                    'sourceTable' => $table,
                                    'sourceId' => $sourceIdArr[$k],
                                    'money' => $checkMoneyArr[$k],
                                ],
                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }


                if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                    if ($json['warn'] == '新增成功') {
                        self::insertOperateLog($id,self::title,"新建");
                    }
                    $this->commitTrans();
                    $idArr = array_filter(array_merge($mxIdArr, $detailIdIdArr));
                    delete(array('table' => self::table . "_detail", 'where' => " id not in ('" . implode("','", $idArr) . "') and orderId = '$id'"));
                    if (in_array($field['type'], ['应付转应付', '应收转应收'])) {
                        delete(array('table' => self::table . "_replace", 'where' => " id not in ('" . implode("','", $replaceIdArr) . "') and orderId = '$id'"));
                    }


                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('writeOffOrder.editEdit.log'));
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 判断收付款单
     */
    public function judgeReceipt($type): bool|string
    {
        $bool = true;
        $mxIdArr = $this->post('mxId') ?: [];
        $mxSourceIdArr = $this->post('mxSourceId');
        $mxMoneyArr = $this->post('mxMoney');
        if ($type == '预收冲应收' || $type == '预付冲应付') {
            foreach ($mxIdArr as $k => $mxId) {
                //收款单
                $targetInfo = query('receipt', "id = '$mxSourceIdArr[$k]'");
                //单据金额
                $totalMoney = find(array('table' => 'receipt_detail', "single" => "orderId = '$targetInfo[id]'", 'sum' => "money"));
                //已核销金额
                $checkMoney = find(array('table' => "receipt_source", "single" => "orderId = '$targetInfo[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                if ($mxMoneyArr[$k] > $totalMoney - $checkMoney) {
                    return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.judgeReceipt.tips'));
                }
            }
        } elseif ($type == '应收转应收' || $type == '应收冲应付') {
            $detailIdIdArr = $mxIdArr;
            $sourceIdArr = $mxSourceIdArr;
            $checkMoneyArr = $mxMoneyArr;
            $targetId = $this->post('targetId');
            foreach ($detailIdIdArr as $k => $mxId) {
                //销售发货单
                $targetInfo = query('sale_send_order', "id = '$sourceIdArr[$k]'");
                //单据金额
                $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$targetInfo[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                if (empty($targetInfo['id'])) {
                    //销售退货单
                    $targetInfo = query('sale_refund_order', "id = '$sourceIdArr[$k]'");
                    //单据金额
                    $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$targetInfo[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                }
                if ($type == '应收冲应付' && $targetInfo['khid'] != $targetId) {
                    //转过的单子
                    $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$targetInfo[id]' and targetIn = '$targetId'", 'sum' => "money"));
                }
                //已核销金额
                $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                if ($checkMoneyArr[$k] > $totalMoney - $checkMoney) {
                    return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.judgeReceipt.tips'));
                }
            }
        } elseif ($type == '应付转应付') {
            $detailIdIdArr = $mxIdArr;
            $sourceIdArr = $mxSourceIdArr;
            $checkMoneyArr = $mxMoneyArr;
            foreach ($detailIdIdArr as $k => $mxId) {
                //采购收货单
                $targetInfo = query('purchase_get_order', "id = '$sourceIdArr[$k]'");
                //单据金额
                $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$targetInfo[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                if (empty($targetInfo['id'])) {
                    //采购退货单
                    $targetInfo = query('purchase_refund_order', "id = '$sourceIdArr[$k]'");
                    //单据金额
                    $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$targetInfo[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                }
                //已核销金额
                $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                if ($checkMoneyArr[$k] > $totalMoney - $checkMoney) {
                    return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.judgeReceipt.tips'));
                }
            }
        }
        return $bool;

    }

    /**
     * 判断应收应付单据是否超出剩余未核销金额
     */
    public function judgeRecMoney($type): bool|string
    {
        $bool = true;
        $detailIdIdArr = $this->post('detailId') ?: [];
        $sourceIdArr = $this->post('sourceId');
        $checkMoneyArr = $this->post('checkMoney');

        if ($type == '预收冲应收') {
            $targetId = $this->post('targetId');
            foreach ($detailIdIdArr as $k => $mxId) {
                //销售发货单
                $targetInfo = query('sale_send_order', "id = '$sourceIdArr[$k]'");
                //单据金额
                $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$targetInfo[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                $orderType = '销售发货单';
                if (empty($targetInfo['id'])) {
                    //销售退货单
                    $orderType = '销售退货单';
                    $targetInfo = query('sale_refund_order', "id = '$sourceIdArr[$k]'");
                    //单据金额
                    $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$targetInfo[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                }
                if ($targetInfo['khid'] != $targetId) {
                    //转过的单子
                    $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$targetInfo[id]' and targetIn = '$targetId'", 'sum' => "money"));
                }
                $totalMoney = $orderType == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                //已核销金额
                $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                if ($checkMoneyArr[$k] > $totalMoney - $checkMoney) {
                    return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.judgeReceipt.tips'));
                }
            }
        } elseif ($type == '预付冲应付' || $type == '应收冲应付') {
            $targetId = $type == '预付冲应付' ? $this->post('targetId') : $this->post('otherId');
            foreach ($detailIdIdArr as $k => $mxId) {
                //采购收货单
                $orderType = '采购收货单';
                $targetInfo = query('purchase_get_order', "id = '$sourceIdArr[$k]'");
                //单据金额
                $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$targetInfo[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];

                if (empty($targetInfo['id'])) {
                    //采购退货单
                    $orderType = '采购退货单';
                    $targetInfo = query('purchase_refund_order', "id = '$sourceIdArr[$k]'");
                    //单据金额
                    $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$targetInfo[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                }
                if ($targetInfo['supplierId'] != $targetId) {
                    //转过的单子
                    $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$targetInfo[id]' and targetIn = '$targetId'", 'sum' => "money"));
                }
                $totalMoney = $orderType == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);

                //已核销金额
                $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                if ($checkMoneyArr[$k] > $totalMoney - $checkMoney) {
                    return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.judgeReceipt.tips'));
                }
            }
        }
        return $bool;
    }

    /**
     * 应付转应付
     */
    public function addShouldPay(): bool|string
    {
        $html =
            select(array("name" => "orderType", "title" => L('writeOffOrder.addShouldPay.orderType'), 'option' => ['采购收货单', '采购退货单'])) .
            text(array("name" => "orderNo", "title" => L('writeOffOrder.addShouldPay.orderNo'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('writeOffOrder.addShouldPay.recordDate'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'otherId', 'value' => $this->post('otherId'))) .
            hidden(array('name' => 'type', 'value' => $this->post('type'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : '')) .
            hidden(array('name' => 'mxSourceId', 'value' => $this->post('mxSourceId') ? implode(',', $this->post('mxSourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addOrder('{$this->post('type')}','pay')\" type='button' class='searchSub' value='" . L('writeOffOrder.addShouldPay.sub') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('writeOffOrder.addShouldPay.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 应付转应付
     * @return bool|string
     */
    public function addShouldPaySearch(): bool|string
    {
        $targetId = $this->post('targetId');
        $sourceId = $this->post('mxSourceId') ? explode(',', $this->post('mxSourceId')) : [];
        $where = " coid='" . self::$coid . "' and supplierId = '$targetId' and id not in ('" . implode("','", $sourceId) . "')";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' => '已确认',
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $whereOne = $whereTwo = '';
        if ($this->post('orderType') == '采购收货单') {
            $whereTwo = " and 1!=1";
        } elseif ($this->post('orderType') == '采购退货单') {
            $whereOne = " and 1!=1";
        }
        $page = $this->page([
            "table" => "purchase_get_order where  {$where} {$whereOne} UNION select id,time from purchase_refund_order",
            'field' => 'id,time',
            "where" => $where . $whereTwo,
            'pageNum' => 50,
            'union' => "select ifnull(count(id),0) as num from purchase_get_order where {$where} UNION select ifnull(count(id),0) as num from purchase_refund_order where {$where}",
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("addShouldPayForm", "orderId");
        $tr[] = [$checkAll, L('writeOffOrder.addShouldPaySearch.orderNo'), L('writeOffOrder.addShouldPaySearch.type'), L('writeOffOrder.addShouldPaySearch.recordDate'), L('writeOffOrder.addShouldPaySearch.totalMoney'), L('writeOffOrder.addShouldPaySearch.checkMoney')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            $info = query('purchase_get_order', "id = '$array[id]'");
            $type = '采购收货单';
            //单据金额
            $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
            if (empty($info['id'])) {
                $info = query('purchase_refund_order', "id = '$array[id]'");
                $type = '采购退货单';
                //单据金额
                $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
            }
            //已核销金额
            $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
            //核销单
            $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
            $tr[] = array(
                $this->dominate($dominate),
                $info['orderNo'],
                $type,
                $info['recordDate'],
                round($totalMoney, 2),
                round($checkMoney, 2)
            );
        }
        $json['html'] = $page['hint'] . "<form name='addShouldPayForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 应付转应付
     */
    public function addShouldPayEdit(): bool|string
    {
        $mxIdArr = $this->post('orderId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.sourceOrder');
        } else {
            $tr = [];
            foreach ($mxIdArr as $id) {
                $info = query('purchase_get_order', "id = '$id'");
                //单据金额
                $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                $type = '采购收货单';
                if (empty($info['id'])) {
                    $info = query('purchase_refund_order', "id = '$id'");
                    //单据金额
                    $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                    $type = '采购退货单';
                }
                $totalMoney = $type == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                //已核销金额
                $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                $checkMoney = round($checkMoney, 2);
                $unCheckMoney = $totalMoney - $checkMoney;
                $uid = self::getId();
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => $uid)) .
                    hidden(array('name' => 'mxSourceId[]', 'value' => $id)),
                    $info['orderNo'],
                    $type,
                    $info['recordDate'],
                    $totalMoney,
                    $checkMoney,
                    $unCheckMoney,
                    text(array('name' => 'mxMoney[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('amount'), 'value' => $unCheckMoney)),
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
        }
        return json_encode($json, 320);
    }

    /**
     * 应收转应收
     */
    public function addShouldRec(): bool|string
    {
        $html =
            select(array("name" => "orderType", "title" => L('writeOffOrder.addShouldPay.orderType'), 'option' => ['销售发货单', '销售退货单'])) .
            text(array("name" => "orderNo", "title" => L('writeOffOrder.addShouldPay.orderNo'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('writeOffOrder.addShouldPay.recordDate'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'otherId', 'value' => $this->post('otherId'))) .
            hidden(array('name' => 'type', 'value' => $this->post('type'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : '')) .
            hidden(array('name' => 'mxSourceId', 'value' => $this->post('mxSourceId') ? implode(',', $this->post('mxSourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addOrder('{$this->post('type')}','rec')\" type='button' class='searchSub' value='" . L('writeOffOrder.addShouldPay.sub') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('writeOffOrder.addShouldPay.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 应收转应收
     * @return bool|string
     */
    public function addShouldRecSearch(): bool|string
    {
        $targetId = $this->post('targetId');
        $sourceId = $this->post('mxSourceId') ? explode(',', $this->post('mxSourceId')) : [];
        $where = " coid='" . self::$coid . "' and khid = '$targetId' and id not in ('" . implode("','", $sourceId) . "')";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' => '已确认',
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $whereOne = $whereTwo = '';
        if ($this->post('orderType') == '销售发货单') {
            $whereTwo = " and 1!=1";
        } elseif ($this->post('orderType') == '销售退货单') {
            $whereOne = " and 1!=1";
        }
        $page = $this->page([
            "table" => "sale_send_order where  {$where} {$whereOne} UNION select id,time from sale_refund_order",
            'field' => 'id,time',
            "where" => $where . $whereTwo,
            'pageNum' => 50,
            'union' => "select ifnull(count(id),0) as num from sale_send_order where {$where} UNION select ifnull(count(id),0) as num from sale_refund_order where {$where}",
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("addShouldRecForm", "orderId");
        $tr[] = [$checkAll, L('writeOffOrder.addShouldPaySearch.orderNo'), L('writeOffOrder.addShouldPaySearch.type'), L('writeOffOrder.addShouldPaySearch.recordDate'), L('writeOffOrder.addShouldPaySearch.totalMoney'), L('writeOffOrder.addShouldPaySearch.checkMoney')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            $info = query('sale_send_order', "id = '$array[id]'");
            $type = '销售发货单';
            //单据金额
            $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];

            if (empty($info['id'])) {
                $info = query('sale_refund_order', "id = '$array[id]'");
                $type = '销售退货单';
                //单据金额
                $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
            }
            //已核销金额
            $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
            //核销单
            $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
            $tr[] = array(
                $this->dominate($dominate),
                $info['orderNo'],
                $type,
                $info['recordDate'],
                round($totalMoney, 2),
                round($checkMoney, 2)
            );
        }
        $json['html'] = $page['hint'] . "<form name='addShouldRecForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 应收转应收
     */
    public function addShouldRecEdit(): bool|string
    {
        $mxIdArr = $this->post('orderId');

        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.sourceOrder');
        } else {
            $tr = [];
            foreach ($mxIdArr as $id) {
                $info = query('sale_send_order', "id = '$id'");
                //单据金额
                $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                $type = '销售发货单';
                if (empty($info['id'])) {
                    $info = query('sale_refund_order', "id = '$id'");
                    //单据金额
                    $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                    $type = '销售退货单';
                }
                $totalMoney = $type == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                //已核销金额
                $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                $checkMoney = round($checkMoney, 2);
                $unCheckMoney = $totalMoney - $checkMoney;
                $uid = self::getId();
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => $uid)) .
                    hidden(array('name' => 'mxSourceId[]', 'value' => $id)),
                    $info['orderNo'],
                    $type,
                    $info['recordDate'],
                    $totalMoney,
                    $checkMoney,
                    $unCheckMoney,
                    text(array('name' => 'mxMoney[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('amount'), 'value' => $unCheckMoney)),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /**
     * 预收
     * @return bool|string
     */
    public function addPreOrder(): bool|string
    {
        $html =
            text(array("name" => "orderNo", "title" => L('writeOffOrder.addShouldPay.receiptOrderNo'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('writeOffOrder.addShouldPay.recordDate'))) .
            hidden(array('name' => 'khid', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addOrder('table_one')\" type='button' class='searchSub' value='" . L('writeOffOrder.addShouldPay.sub') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('writeOffOrder.addShouldPay.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 预收
     * @return bool|string
     */
    public function addPreOrderSearch(): bool|string
    {
        $khid = $this->post('khid');
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $and = " and classify = 1 and coid='" . self::$coid . "' and targetId = '$khid' and id not in ('" . implode("','", $sourceId) . "')";
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' => '已确认',
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "receipt",
            "where" => $where,
            'pageNum' => 50,
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("addPreOrderForm", "orderId");
        $tr[] = [$checkAll, L('writeOffOrder.addShouldPaySearch.orderNo'), L('writeOffOrder.addShouldPaySearch.type'), L('writeOffOrder.addShouldPaySearch.recordDate'), L('writeOffOrder.addShouldPaySearch.totalMoney'), L('writeOffOrder.addShouldPaySearch.checkMoney')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            //单据金额
            $totalMoney = find(array('table' => 'receipt_detail', "where" => "orderId = '$array[id]'", 'sum' => "money"));
            //已核销金额
            $checkMoney = find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$array[id]'", 'sum' => "money"));
            $checkMoney += find(array('table' => "receipt_source", "single" => "orderId = '$array[id]'", 'sum' => "money"));
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                L('writeOffOrder.edit.receipt'),
                $array['recordDate'],
                round($totalMoney, 2),
                round($checkMoney, 2)
            );
        }
        $json['html'] = $page['hint'] . "<form name='addPreOrderForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 预收
     */
    public function addPreOrderEdit(): bool|string
    {
        $mxIdArr = $this->post('orderId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.sourceOrder');
        } else {
            $tr = [];
            foreach ($mxIdArr as $id) {
                $info = query('receipt', "id = '$id'");
                //单据金额
                $totalMoney = find(array('table' => 'receipt_detail', "where" => "orderId = '$info[id]'", 'sum' => "money"));
                //已核销金额
                $checkMoney = find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                $checkMoney += find(array('table' => "receipt_source", "single" => "orderId = '$info[id]'", 'sum' => "money"));
                $totalMoney = round($totalMoney, 2);
                $checkMoney = round($checkMoney, 2);
                $unCheckMoney = $totalMoney - $checkMoney;
                $uid = self::getId();
                $receiptWord = L('writeOffOrder.edit.receipt');
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => $uid)) .
                    hidden(array('name' => 'mxSourceId[]', 'value' => $id)),
                    $info['orderNo'],
                    $receiptWord,
                    $info['recordDate'],
                    $totalMoney,
                    $checkMoney,
                    $unCheckMoney,
                    text(array('name' => 'mxMoney[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('amount'), 'value' => $unCheckMoney)),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 预付
     * @return bool|string
     */
    public function addPayOrder(): bool|string
    {
        $html =
            text(array("name" => "orderNo", "title" => L('writeOffOrder.addShouldPay.paymentOrderNo'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('writeOffOrder.addShouldPay.recordDate'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addOrder('addPayOrder')\" type='button' class='searchSub' value='" . L('writeOffOrder.addShouldPay.sub') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('writeOffOrder.addShouldPay.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 预付
     * @return bool|string
     */
    public function addPayOrderSearch(): bool|string
    {
        $supplierId = $this->post('targetId');
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $and = " and classify = 0 and coid='" . self::$coid . "' and targetId = '$supplierId' and id not in ('" . implode("','", $sourceId) . "')";
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' => '已确认',
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "receipt",
            "where" => $where,
            'pageNum' => 50,
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("addPayOrderForm", "orderId");
        $tr[] = [$checkAll, L('writeOffOrder.addShouldPaySearch.orderNo'), L('writeOffOrder.addShouldPaySearch.type'), L('writeOffOrder.addShouldPaySearch.recordDate'), L('writeOffOrder.addShouldPaySearch.totalMoney'), L('writeOffOrder.addShouldPaySearch.checkMoney')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            //单据金额
            $totalMoney = find(array('table' => 'receipt_detail', "where" => "orderId = '$array[id]'", 'sum' => "money"));
            //已核销金额
            $checkMoney = find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$array[id]'", 'sum' => "money"));
            $checkMoney += find(array('table' => "receipt_source", "single" => "orderId = '$array[id]'", 'sum' => "money"));
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                L('writeOffOrder.edit.payment'),
                $array['recordDate'],
                round($totalMoney, 2),
                round($checkMoney, 2)
            );
        }
        $json['html'] = $page['hint'] . "<form name='addPayOrderForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 预付
     */
    public function addPayOrderEdit(): bool|string
    {
        $mxIdArr = $this->post('orderId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.sourceOrder');
        } else {
            $tr = [];
            foreach ($mxIdArr as $id) {
                $info = query('receipt', "id = '$id'");
                //单据金额
                $totalMoney = find(array('table' => 'receipt_detail', "where" => "orderId = '$info[id]'", 'sum' => "money"));
                //已核销金额
                $checkMoney = find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                $checkMoney += find(array('table' => "receipt_source", "single" => "orderId = '$info[id]'", 'sum' => "money"));
                $totalMoney = round($totalMoney, 2);
                $checkMoney = round($checkMoney, 2);
                $unCheckMoney = $totalMoney - $checkMoney;
                $uid = self::getId();
                $paymentWord = L('writeOffOrder.edit.payment');
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => $uid)) .
                    hidden(array('name' => 'mxSourceId[]', 'value' => $id)),
                    $info['orderNo'],
                    $paymentWord,
                    $info['recordDate'],
                    $totalMoney,
                    $checkMoney,
                    $unCheckMoney,
                    text(array('name' => 'mxMoney[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('amount'), 'value' => $unCheckMoney)),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 应收
     * @return bool|string
     */
    public function addRecOrder(): bool|string
    {
        $html =
            select(array("name" => "orderType", "title" => L('writeOffOrder.addShouldPay.orderType'), 'option' => ['销售发货单', '销售退货单'])) .
            text(array("name" => "orderNo", "title" => L('writeOffOrder.addShouldPay.orderNo'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('writeOffOrder.addShouldPay.recordDate'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'otherId', 'value' => $this->post('otherId'))) .
            hidden(array('name' => 'type', 'value' => $this->post('type'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : '')) .
            hidden(array('name' => 'mxSourceId', 'value' => $this->post('mxSourceId') ? implode(',', $this->post('mxSourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addOrder('{$this->post('type')}','rec')\" type='button' class='searchSub' value='" . L('writeOffOrder.addShouldPay.sub') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('writeOffOrder.addShouldPay.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 应收
     * @return bool|string
     */
    public function addRecOrderSearch(): bool|string
    {
        $targetId = $this->post('targetId');
        if (in_array($this->post('type'), ['应收转应收', '应收冲应付'])) {
            $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        } else {
            $sourceId = $this->post('mxSourceId') ? explode(',', $this->post('mxSourceId')) : [];
        }
        $where = " coid='" . self::$coid . "' and (khid = '$targetId' or id in (select distinct sourceId from write_off_order_replace where targetIn = '$targetId' and coid = '" . self::$coid . "' and type = '应收转应收')) and id not in ('" . implode("','", $sourceId) . "')";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' => '已确认',
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $whereOne = $whereTwo = '';
        if ($this->post('orderType') == '销售发货单') {
            $whereTwo = " and 1!=1";
        } elseif ($this->post('orderType') == '销售退货单') {
            $whereOne = " and 1!=1";
        }
        $page = $this->page([
            "table" => "sale_send_order where  {$where} {$whereOne} UNION select id,time from sale_refund_order",
            'field' => 'id,time',
            "where" => $where . $whereTwo,
            'pageNum' => 50,
            'union' => "select ifnull(count(id),0) as num from sale_send_order where {$where} UNION select ifnull(count(id),0) as num from sale_refund_order where {$where}",
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("addRecOrderForm", "orderId");
        $tr[] = [$checkAll, L('writeOffOrder.addShouldPaySearch.orderNo'), L('writeOffOrder.addShouldPaySearch.type'), L('writeOffOrder.addShouldPaySearch.recordDate'), L('writeOffOrder.addShouldPaySearch.settlementType'), L('writeOffOrder.addShouldPaySearch.period'), L('writeOffOrder.addShouldPaySearch.totalMoney'), L('writeOffOrder.addShouldPaySearch.checkMoney')];
        $inReceipt = new inReceiptClass();
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            $info = query('sale_send_order', "id = '$array[id]'");
            $type = '销售发货单';
            $settlementType = '';
            $period = '';
            //单据金额
            $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
            if (empty($info['id'])) {
                $info = query('sale_refund_order', "id = '$array[id]'");
                $type = '销售退货单';
                //单据金额
                $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
            } else {
                $settlementType = $info['settlementType'];
                $period = $inReceipt->settlementPeriod($info['settlementType'], $info['recordDate'], $info['settlementDay']);
            }
            if ($info['khid'] != $targetId) {
                //转过的单子
                $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$info[id]' and targetIn = '$targetId'", 'sum' => "money"));
            }
            //已核销金额
            $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
            //核销单
            $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
            $tr[] = array(
                $this->dominate($dominate),
                $info['orderNo'],
                $type,
                $info['recordDate'],
                $settlementType,
                $period,
                round($totalMoney, 2),
                round($checkMoney, 2)
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='addRecOrderForm'>" .
                hidden(array('name' => 'targetId', 'value' => $targetId)) .
                hidden(array('name' => 'type', 'value' => $this->post('type'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 应收
     */
    public function addRecOrderEdit(): bool|string
    {
        $targetId = $this->post('targetId');
        $mxIdArr = $this->post('orderId');
        $classify = $this->post('type');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.sourceOrder');
        } elseif (empty($classify)) {
            $json['warn'] = L('writeOffOrder.addRecOrderEdit.typeEmpty');
        } elseif (empty($targetId)) {
            $json['warn'] = L('writeOffOrder.addRecOrderEdit.objEmpty');
        } else {
            $tr = [];
            $inReceipt = new inReceiptClass();
            foreach ($mxIdArr as $id) {
                $settlementType = '';
                $period = '';
                $info = query('sale_send_order', "id = '$id'");
                //单据金额
                $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                $type = '销售发货单';
                if (empty($info['id'])) {
                    $info = query('sale_refund_order', "id = '$id'");
                    //单据金额
                    $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                    $type = '销售退货单';
                } else {
                    $settlementType = $info['settlementType'];
                    $period = $inReceipt->settlementPeriod($info['settlementType'], $info['recordDate'], $info['settlementDay']);
                }
                if ($info['khid'] != $targetId) {
                    //转过的单子
                    $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$info[id]' and targetIn = '$targetId'", 'sum' => "money"));
                }

                $totalMoney = $type == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);

                //已核销金额
                $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                $checkMoney = round($checkMoney, 2);
                $unCheckMoney = $totalMoney - $checkMoney;
                $uid = self::getId();
                if ($classify == '预收冲应收') {
                    $tr[]              = [
                        componentClass::tablePperation('',"delTableRow(this)").
                        hidden(array('name' => 'detailId[]', 'value' => $uid)) .
                        hidden(array('name' => 'sourceId[]', 'value' => $id)),
                        $info['orderNo'],
                        $type,
                        $info['recordDate'],
                        $settlementType,
                        $period,
                        $totalMoney,
                        $checkMoney,
                        $unCheckMoney,
                        text(array('name' => 'checkMoney[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('amount'), 'value' => $unCheckMoney)),
                    ];
                } else {
                    $tr[]              = [
                        componentClass::tablePperation('',"delTableRow(this)").
                        hidden(array('name' => 'mxId[]', 'value' => $uid)) .
                        hidden(array('name' => 'mxSourceId[]', 'value' => $id)),
                        $info['orderNo'],
                        $type,
                        $info['recordDate'],
                        $settlementType,
                        $period,
                        $totalMoney,
                        $checkMoney,
                        $unCheckMoney,
                        text(array('name' => 'mxMoney[]', 'other' => self::digitalFiltering('amount'), 'value' => $unCheckMoney)),
                    ];
                }
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 应付
     * @return bool|string
     */
    public function addBuyOrder(): bool|string
    {
        $html =
            select(array("name" => "orderType", "title" => L('writeOffOrder.addShouldPay.orderType'), 'option' => ['采购收货单', '采购退货单'])) .
            text(array("name" => "orderNo", "title" => L('writeOffOrder.addShouldPay.orderNo'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('writeOffOrder.addShouldPay.recordDate'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'otherId', 'value' => $this->post('otherId'))) .
            hidden(array('name' => 'type', 'value' => $this->post('type'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : '')) .
            hidden(array('name' => 'mxSourceId', 'value' => $this->post('mxSourceId') ? implode(',', $this->post('mxSourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addOrder('{$this->post('type')}','pay')\" type='button' class='searchSub' value='" . L('writeOffOrder.addShouldPay.sub') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('writeOffOrder.addShouldPay.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 应付
     * @return bool|string
     */
    public function addBuyOrderSearch(): bool|string
    {
        if (in_array($this->post('type'), ['预付冲应付'])) {
            $targetId = $this->post('targetId');
        } else {
            $targetId = $this->post('otherId');
        }
        if (in_array($this->post('type'), ['预付冲应付', '应收冲应付'])) {
            $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        } else {
            $sourceId = $this->post('mxSourceId') ? explode(',', $this->post('mxSourceId')) : [];
        }
        $where = " coid='" . self::$coid . "' and (supplierId = '$targetId' or id in (select distinct sourceId from write_off_order_replace where targetIn = '$targetId' and coid = '" . self::$coid . "' and type = '应付转应付')) and id not in ('" . implode("','", $sourceId) . "')";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' => '已确认',
        ];
        $whereOne = $whereTwo = '';
        if ($this->post('orderType') == '采购收货单') {
            $whereTwo = " and 1!=1";
        } elseif ($this->post('orderType') == '采购退货单') {
            $whereOne = " and 1!=1";
        }
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "purchase_get_order where  {$where} {$whereOne}  UNION select id,time from purchase_refund_order",
            'field' => 'id,time',
            "where" => $where . $whereTwo,
            'pageNum' => 50,
            'union' => "select ifnull(count(id),0) as num from purchase_get_order where {$where} UNION select ifnull(count(id),0) as num from purchase_refund_order where {$where}",
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("addBuyOrderForm", "orderId");
        $tr[] = [$checkAll, L('writeOffOrder.addShouldPaySearch.orderNo'), L('writeOffOrder.addShouldPaySearch.type'), L('writeOffOrder.addShouldPaySearch.recordDate'), L('writeOffOrder.addShouldPaySearch.settlementType'), L('writeOffOrder.addShouldPaySearch.period'), L('writeOffOrder.addShouldPaySearch.totalMoney'), L('writeOffOrder.addShouldPaySearch.checkMoney')];
        $inReceipt = new inReceiptClass();
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            $settlementType = '';
            $period = '';
            $info = query('purchase_get_order', "id = '$array[id]'");
            $type = '采购收货单';
            //单据金额
            $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
            if (empty($info['id'])) {
                $info = query('purchase_refund_order', "id = '$array[id]'");
                $type = '采购退货单';
                //单据金额
                $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
            } else {
                $settlementType = $info['settlementType'];
                $period = $inReceipt->settlementPeriod($info['settlementType'], $info['recordDate'], $info['settlementDay']);
            }

            if ($info['supplierId'] != $targetId) {
                //转过的单子
                $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$info[id]' and targetIn = '$targetId'", 'sum' => "money"));
            }

            //已核销金额
            $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
            //核销单
            $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
            $tr[] = array(
                $this->dominate($dominate),
                $info['orderNo'],
                $type,
                $info['recordDate'],
                $settlementType,
                $period,
                round($totalMoney, 2),
                round($checkMoney, 2)
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='addBuyOrderForm'>" .
                hidden(array('name' => 'type', 'value' => $this->post('type'))) .
                hidden(array('name' => 'targetId', 'value' => $targetId)) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 应付
     */
    public function addBuyOrderEdit(): bool|string
    {
        $mxIdArr = $this->post('orderId');
        $classify = $this->post('type');
        $targetId = $this->post('targetId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('writeOffOrder.addShouldPayEdit.sourceOrder');
        } elseif (empty($classify)) {
            $json['warn'] = L('writeOffOrder.addRecOrderEdit.typeEmpty');
        } elseif (empty($targetId)) {
            $json['warn'] = L('writeOffOrder.addRecOrderEdit.objEmpty');
        } else {
            $tr = [];
            $inReceipt = new inReceiptClass();
            foreach ($mxIdArr as $id) {
                $settlementType = '';
                $period = '';
                $info = query('purchase_get_order', "id = '$id'");
                //单据金额
                $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                $type = '采购收货单';
                if (empty($info['id'])) {
                    $info = query('purchase_refund_order', "id = '$id'");
                    //单据金额
                    $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$info[id]'", 'field' => "ifnull(sum(b.money),0) as total"))['total'];
                    $type = '采购退货单';
                } else {
                    $settlementType = $info['settlementType'];
                    $period = $inReceipt->settlementPeriod($info['settlementType'], $info['recordDate'], $info['settlementDay']);
                }
                if ($info['supplierId'] != $targetId) {
                    //转过的单子
                    $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$info[id]' and targetIn = '$targetId'", 'sum' => "money"));
                }
                $totalMoney = $type == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                //已核销金额
                $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                //核销单
                $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$info[id]'", 'sum' => "money"));
                $checkMoney = round($checkMoney, 2);
                $unCheckMoney = $totalMoney - $checkMoney;
                $uid = self::getId();
                if ($classify == '应付转应付') {
                    $tr[]              = [
                        componentClass::tablePperation('',"delTableRow(this)").
                        hidden(array('name' => 'mxId[]', 'value' => $uid)) .
                        hidden(array('name' => 'mxSourceId[]', 'value' => $id)),
                        $info['orderNo'],
                        $type,
                        $info['recordDate'],
                        $settlementType,
                        $period,
                        $totalMoney,
                        $checkMoney,
                        $unCheckMoney,
                        text(array('name' => 'mxMoney[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('amount'), 'value' => $unCheckMoney)),
                    ];
                } else {
                    $tr[]              = [
                        componentClass::tablePperation('',"delTableRow(this)").
                        hidden(array('name' => 'detailId[]', 'value' => $uid)) .
                        hidden(array('name' => 'sourceId[]', 'value' => $id)),
                        $info['orderNo'],
                        $type,
                        $info['recordDate'],
                        $settlementType,
                        $period,
                        $totalMoney,
                        $checkMoney,
                        $unCheckMoney,
                        text(array('name' => 'checkMoney[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('amount'), 'value' => $unCheckMoney)),
                    ];
                }

            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 销售或采购单据金额
     */
    private static function sale_money($sourceTable, $sourceId)
    {
        $totalMoney = 0;
        if ($sourceTable == 'sale_send_order') {
            //单据金额
            $totalMoney = find(array('table' => 'sale_send_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$sourceId'", 'field' => "ifnull(sum(b.money),0) as total"))['total'] ?? 0;
        } elseif ($sourceTable == 'sale_refund_order') {
            //单据金额
            $totalMoney = find(array('table' => 'sale_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$sourceId'", 'field' => "ifnull(sum(b.money),0) as total"))['total'] ?? 0;
        } elseif ($sourceTable == 'purchase_get_order') {
            //单据金额
            $totalMoney = find(array('table' => 'purchase_get_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$sourceId'", 'field' => "ifnull(sum(b.money),0) as total"))['total'] ?? 0;
        } elseif ($sourceTable == 'purchase_refund_order') {
            //单据金额
            $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join inventory_detail as b on a.id = b.sourceId', "single" => "a.orderId = '$sourceId'", 'field' => "ifnull(sum(b.money),0) as total"))['total'] ?? 0;
        }
        return $totalMoney;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('writeOffOrder.detail.power');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => L('writeOffOrder.detail.edit'),
                        "type" => "顶部页卡",
                        "title" => L('writeOffOrder.detail.editDetail'),
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&type={$info['type']}&id=" . $info['id'],

                    ];
                    if ($info['state'] == '草稿') {
                        //按钮
                        $button[] = [
                            "name" => L('writeOffOrder.detail.sub'),
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'commit', "id" => $info['id']],
                            'style' => 'li-btn-blue-bg',
                        ];
                    }
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => L('writeOffOrder.detail.del'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }

            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => L('writeOffOrder.detail.sure'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $inReceipt = new inReceiptClass();

            $lineOne = $lineTwo = [];
            $tr[] = [L('writeOffOrder.addShouldPaySearch.orderNo'), L('writeOffOrder.addShouldPaySearch.type'), L('writeOffOrder.addShouldPaySearch.recordDate'), L('writeOffOrder.addShouldPaySearch.totalMoney') . '(' . static::$unit . ')', L('writeOffOrder.addShouldPaySearch.checkMoney') . '(' . static::$unit . ')', L('writeOffOrder.addShouldPaySearch.unOffMoney') . '(' . static::$unit . ')', L('writeOffOrder.addShouldPaySearch.offMoney') . '(' . static::$unit . ')'];
            $sourceTr[] = [L('writeOffOrder.addShouldPaySearch.orderNo'), L('writeOffOrder.addShouldPaySearch.type'), L('writeOffOrder.addShouldPaySearch.recordDate'), L('writeOffOrder.addShouldPaySearch.settlementType'), L('writeOffOrder.addShouldPaySearch.period'), L('writeOffOrder.addShouldPaySearch.totalMoney') . '(' . static::$unit . ')', L('writeOffOrder.addShouldPaySearch.checkMoney') . '(' . static::$unit . ')', L('writeOffOrder.addShouldPaySearch.unOffMoney') . '(' . static::$unit . ')', L('writeOffOrder.addShouldPaySearch.offMoney') . '(' . static::$unit . ')'];
            $receiptOneMoney = $receiptTwoMoney = 0;//单据金额
            $receiptOneOffMoney = $receiptTwoOffMoney = 0;//已核销金额
            $offOneMoney = $offTwoMoney = 0;//本次核销金额
            switch ($info['type']) {
                case '预收冲应收':
                    /******预收*********/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '预收' order by list"));
                    foreach ($result['array'] as $array) {
                        $mx = query('receipt', "id = '$array[sourceId]'");
                        $orderType = '';
                        if ($mx['classify'] == 1) {
                            $orderType = L('writeOffOrder.edit.receipt');
                        } elseif ($mx['classify'] == 0) {
                            $orderType = L('writeOffOrder.edit.payment');
                        }
                        //单据金额
                        $totalMoney = find(array('table' => 'receipt_detail', "where" => "orderId = '$mx[id]'", 'sum' => "money"));
                        $receiptOneMoney += $totalMoney;
                        //已核销金额
                        $checkMoney = find(array('table' => 'receipt_source', "where" => "orderId = '$mx[id]'", 'sum' => "money"));
                        //核销单(从收款单中找)
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $receiptOneOffMoney += $checkMoney;
                        $offOneMoney += $array['money'];
                        $tr[] = [
                            $mx['orderNo'],
                            $orderType,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            $array['money'],
                        ];
                    }
                    /******应收*********/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收' order by list"));
                    foreach ($result['array'] as $array) {
                        $settlementType = '';
                        $period = '';
                        if ($array['sourceTable'] == 'sale_send_order') {
                            $type = '销售发货单';
                            $mx = query('sale_send_order', "id = '$array[sourceId]'");
                            $settlementType = $mx['settlementType'];
                            $period = $inReceipt->settlementPeriod($mx['settlementType'], $mx['recordDate'], $mx['settlementDay']);
                        } else {
                            $type = '销售退货单';
                            $mx = query('sale_refund_order', "id = '$array[sourceId]'");
                        }
                        //单据金额
                        $totalMoney = self::sale_money($array['sourceTable'], $array['sourceId']);
                        if ($mx['khid'] != $info['targetId']) {
                            //转过的单子
                            $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$mx[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                        }
                        $totalMoney = $type == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $receiptTwoMoney += $totalMoney;
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $receiptTwoOffMoney += $checkMoney;
                        $offTwoMoney += $array['money'];
                        $sourceTr[] = [
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            $settlementType,
                            $period,
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            $array['money'],
                        ];
                    }
                    $kehu = query('kehu', "khid = '$info[targetId]'");
                    $lineOne = array(
                        L('writeOffOrder.detail.type') => $info['type'],
                        L('writeOffOrder.detail.targetName') => $kehu['companyName'],
                        L('writeOffOrder.detail.recordDate') => $info['recordDate'],
                    );
                    $lineTwo = array(
                        L('writeOffOrder.detail.text') => pre($info['text']),
                    );
                    $titleOne = '预收单据';
                    $titleTwo = '应收单据';
                    $total_tr = [
                            3=>$receiptOneMoney,
                            4=>$receiptOneOffMoney,
                            5=>($receiptOneMoney - $receiptOneOffMoney),
                            6=>$offOneMoney
                        ];
                    $total_source_tr[] = [
                            5=>$receiptTwoMoney,
                            6=>$receiptTwoOffMoney,
                            7=>($receiptTwoMoney - $receiptTwoOffMoney),
                            8=>$offTwoMoney
                    ];
                    $tableOne = $this->listTable(array('tr' => $tr, 'total' => $total_tr, 'showSort' => true));
                    $tableTwo = $this->listTable(array('tr' => $sourceTr, 'total' => $total_source_tr, 'showSort' => true));
                    break;
                case '预付冲应付':
                    /******预付*********/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '预付' order by list"));
                    foreach ($result['array'] as $array) {
                        $mx = query('receipt', "id = '$array[sourceId]'");
                        $orderType = '';
                        if ($mx['classify'] == 1) {
                            $orderType = L('writeOffOrder.edit.receipt');
                        } elseif ($mx['classify'] == 0) {
                            $orderType = L('writeOffOrder.edit.payment');
                        }
                        //单据金额
                        $totalMoney = find(array('table' => 'receipt_detail', "where" => "orderId = '$mx[id]'", 'sum' => "money"));
                        $receiptOneMoney += $totalMoney;
                        //已核销金额
                        $checkMoney = find(array('table' => 'receipt_source', "where" => "orderId = '$mx[id]'", 'sum' => "money"));
                        //核销单(从收款单中找)
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $receiptOneOffMoney += $checkMoney;
                        $offOneMoney += $array['money'];
                        $tr[] = [
                            $mx['orderNo'],
                            $orderType,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            $array['money'],
                        ];
                    }
                    /******应付*********/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付' order by list"));
                    foreach ($result['array'] as $array) {
                        $settlementType = '';
                        $period = '';
                        if ($array['sourceTable'] == 'purchase_get_order') {
                            $type = '采购收货单';
                            $mx = query('purchase_get_order', "id = '$array[sourceId]'");
                            $settlementType = $mx['settlementType'];
                            $period = $inReceipt->settlementPeriod($mx['settlementType'], $mx['recordDate'], $mx['settlementDay']);
                        } else {
                            $type = '采购退货单';
                            $mx = query('purchase_refund_order', "id = '$array[sourceId]'");
                        }
                        //单据金额
                        $totalMoney = self::sale_money($array['sourceTable'], $array['sourceId']);
                        if ($mx['supplierId'] != $info['targetId']) {
                            //转过的单子
                            $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$mx[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                        }
                        $totalMoney = $type == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $receiptTwoMoney += $totalMoney;
                        $receiptTwoOffMoney += $checkMoney;
                        $offTwoMoney += $array['money'];
                        $sourceTr[] = [
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            $settlementType,
                            $period,
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            $array['money'],
                        ];
                    }
                    $supplier = query('supplier', "id = '$info[targetId]'");
                    $lineOne = array(
                        L('writeOffOrder.detail.type') => $info['type'],
                        L('writeOffOrder.detail.supplier') => $supplier['name'],
                        L('writeOffOrder.detail.recordDate') => $info['recordDate'],
                    );
                    $lineTwo = array(
                        L('writeOffOrder.detail.text') => pre($info['text']),
                    );
                    $titleOne = '预付单据';
                    $titleTwo = '应付单据';
                    $total_tr[] = [
                            3=>$receiptOneMoney,
                            4=>$receiptOneOffMoney,
                            5=>($receiptOneMoney - $receiptOneOffMoney),
                            6=>$offOneMoney
                        ];
                    $total_source_tr[] = [
                            5=>$receiptTwoMoney,
                            6=>$receiptTwoOffMoney,
                            7=>($receiptTwoMoney - $receiptTwoOffMoney),
                            8=>$offTwoMoney
                        ];
                    $tableOne = $this->listTable(array('tr' => $tr, 'total' => $total_tr, 'showSort' => true));
                    $tableTwo = $this->listTable(array('tr' => $sourceTr, 'total' => $total_source_tr, 'showSort' => true));
                    break;
                case '应收冲应付':
                    /******应收*********/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收' order by list"));
                    foreach ($result['array'] as $array) {
                        if ($array['sourceTable'] == 'sale_send_order') {
                            $type = '销售发货单';
                            $mx = query('sale_send_order', "id = '$array[sourceId]'");
                        } else {
                            $type = '销售退货单';
                            $mx = query('sale_refund_order', "id = '$array[sourceId]'");
                        }
                        //单据金额
                        $totalMoney = self::sale_money($array['sourceTable'], $array['sourceId']);
                        if ($mx['khid'] != $info['targetId']) {
                            //转过的单子
                            $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$mx[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                        }
                        $totalMoney = $type == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        //统计
                        $receiptOneMoney += $totalMoney;
                        $receiptOneOffMoney += $checkMoney;
                        $offOneMoney += $array['money'];
                        $tr[] = [
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            $array['money'],
                        ];
                    }
                    /******应付*********/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付' order by list"));
                    foreach ($result['array'] as $array) {
                        $settlementType = '';
                        $period = '';
                        if ($array['sourceTable'] == 'purchase_get_order') {
                            $type = '采购收货单';
                            $mx = query('purchase_get_order', "id = '$array[sourceId]'");
                            $settlementType = $mx['settlementType'];
                            $period = $inReceipt->settlementPeriod($mx['settlementType'], $mx['recordDate'], $mx['settlementDay']);
                        } else {
                            $type = '采购退货单';
                            $mx = query('purchase_refund_order', "id = '$array[sourceId]'");
                        }
                        //单据金额
                        $totalMoney = self::sale_money($array['sourceTable'], $array['sourceId']);
                        if ($mx['supplierId'] != $info['otherId']) {
                            //转过的单子
                            $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$mx[id]' and targetIn = '$info[otherId]'", 'sum' => "money"));
                        }
                        $totalMoney = $type == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $receiptTwoMoney += $totalMoney;
                        $receiptTwoOffMoney += $checkMoney;
                        $offTwoMoney += $array['money'];
                        $sourceTr[] = [
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            $settlementType,
                            $period,
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            $array['money'],
                        ];
                    }
                    $kehu = query('kehu', "khid = '$info[targetId]'");
                    $lineOne = array(
                        L('writeOffOrder.detail.type') => $info['type'],
                        L('writeOffOrder.detail.targetName') => $kehu['companyName'],
                        L('writeOffOrder.detail.recordDate') => $info['recordDate'],
                    );
                    $lineTwo = array(
                        L('writeOffOrder.detail.text') => pre($info['text']),
                    );
                    $titleOne = '应收单据';
                    $titleTwo = '应付单据';
                    $total_tr[] = [
                            3=>$receiptOneMoney,
                            4=>$receiptOneOffMoney,
                            5=>($receiptOneMoney - $receiptOneOffMoney),
                            6=>$offOneMoney
                        ];
                    $total_source_tr[] = [
                            5=>$receiptTwoMoney,
                            6=>$receiptTwoOffMoney,
                            7=>($receiptTwoMoney - $receiptTwoOffMoney),
                            8=>$offTwoMoney
                        ];
                    $tableOne = $this->listTable(array('tr' => $tr, 'total' => $total_tr, 'showSort' => true));
                    $tableTwo = $this->listTable(array('tr' => $sourceTr, 'total' => $total_source_tr, 'showSort' => true));
                    break;
                case '应收转应收':
                    /******应收*********/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收' order by list"));
                    foreach ($result['array'] as $array) {
                        if ($array['sourceTable'] == 'sale_send_order') {
                            $type = '销售发货单';
                            $mx = query('sale_send_order', "id = '$array[sourceId]'");
                        } else {
                            $type = '销售退货单';
                            $mx = query('sale_refund_order', "id = '$array[sourceId]'");
                        }
                        //单据金额
                        $totalMoney = self::sale_money($array['sourceTable'], $array['sourceId']);
                        $totalMoney = $type == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        //统计
                        $receiptOneMoney += $totalMoney;
                        $receiptOneOffMoney += $checkMoney;
                        $offOneMoney += $array['money'];
                        $tr[] = [
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            $array['money'],
                        ];
                    }
                    $kehuOut = query('kehu', "khid = '$info[targetId]'");
                    $kehuIn = query('kehu', "khid = '$info[otherId]'");
                    $lineOne = array(
                        L('writeOffOrder.detail.type') => $info['type'],
                        L('writeOffOrder.detail.rollOutClient') => $kehuOut['companyName'],
                        L('writeOffOrder.detail.rollInClient') => $kehuIn['companyName'],
                        L('writeOffOrder.detail.recordDate') => $info['recordDate'],
                    );
                    $lineTwo = array(
                        L('writeOffOrder.detail.text') => pre($info['text']),
                    );
                    $titleOne = '应收单据';
                    $titleTwo = '';
                    $total_tr[] = [
                            3=>$receiptOneMoney,
                            4=>$receiptOneOffMoney,
                            5=>($receiptOneMoney - $receiptOneOffMoney),
                            6=>$offOneMoney
                        ];
                    $tableOne = $this->listTable(array('tr' => $tr, 'total' => $total_tr, 'showSort' => true));
                    $tableTwo = '';
                    break;
                case '应付转应付':
                    /******应付*********/
                    $result = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付' order by list"));
                    foreach ($result['array'] as $array) {
                        if ($array['sourceTable'] == 'purchase_get_order') {
                            $type = '采购收货单';
                            $mx = query('purchase_get_order', "id = '$array[sourceId]'");
                        } else {
                            $type = '采购退货单';
                            $mx = query('purchase_refund_order', "id = '$array[sourceId]'");
                        }
                        //单据金额
                        $totalMoney = self::sale_money($array['sourceTable'], $array['sourceId']);
                        $totalMoney = $type == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                        $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "where" => "b.state = '已确认' and a.sourceId = '$mx[id]'", 'sum' => "money"));
                        $receiptOneMoney += $totalMoney;
                        $receiptOneOffMoney += $checkMoney;
                        $offOneMoney += $array['money'];
                        $tr[] = [
                            $mx['orderNo'],
                            $type,
                            $mx['recordDate'],
                            round($totalMoney, 2),
                            round($checkMoney, 2),
                            round($totalMoney - $checkMoney, 2),
                            $array['money'],
                        ];
                    }
                    $supplierOut = query('supplier', "id = '$info[targetId]'");
                    $supplierIn = query('supplier', "id = '$info[otherId]'");
                    $lineOne = array(
                        L('writeOffOrder.detail.type') => $info['type'],
                        L('writeOffOrder.detail.rollOutSupplier') => $supplierOut['name'],
                        L('writeOffOrder.detail.rollInSupplier') => $supplierIn['name'],
                        L('writeOffOrder.detail.recordDate') => $info['recordDate'],
                    );
                    $lineTwo = array(
                        L('writeOffOrder.detail.text') => pre($info['text']),
                    );
                    $titleOne = '应付单据';
                    $titleTwo = '';
                    $total_tr[] = [
                            3=>$receiptOneMoney,
                            4=>$receiptOneOffMoney,
                            5=>($receiptOneMoney - $receiptOneOffMoney),
                            6=>$offOneMoney
                        ];
                    $tableOne = $this->listTable(array('tr' => $tr, 'total' => $total_tr, 'showSort' => true));
                    $tableTwo = '';
                    break;
                default:
                    $titleOne = $titleTwo = '';
                    $tableOne = $tableTwo = '';
                    break;
            }

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    $lineOne,
                    $lineTwo,
                    array(
                        L('writeOffOrder.detail.orderNo') => $info['orderNo'],
                        L('writeOffOrder.detail.stid') => self::findStaff($info['stid']),
                        L('writeOffOrder.detail.state') => $info['state']
                    ),
                ),
            ));
            if($titleOne) {
                $data['html'] .= $this->detailList([
                    'title' => $titleOne,
                    'html' => $tableOne,
                ]);
            }
            if($titleTwo) {
                $data['html'] .= $this->detailList([
                    'title' => $titleTwo,
                    'html' => $tableTwo,
                ]);
            }
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 判断核算金额是否超出剩余核算金额
     */
    public function compute($info): array|string
    {
        $writeOffArray = [];
        switch ($info['type']) {
            case '预付冲应付':
                $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' and classify = '预付' order by list"));
                foreach ($all['array'] as $array) {
                    //收款单
                    $targetInfo = query('receipt', "id = '$array[sourceId]'");
                    //单据金额
                    $totalMoney = find(array('table' => 'receipt_detail', "single" => "orderId = '$targetInfo[id]'", 'sum' => "money"));
                    //已核销金额
                    $checkMoney = find(array('table' => "receipt_source", "single" => "orderId = '$targetInfo[id]'", 'sum' => "money"));
                    //核销单
                    $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    if ($array['money'] > $totalMoney - $checkMoney) {
                        return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.compute.tips'));
                    }
                }
                $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' and classify = '应付' order by list"));
                foreach ($all['array'] as $array) {
                    //采购收货单
                    $orderType = '采购收货单';
                    $targetInfo = query('purchase_get_order', "id = '$array[sourceId]'");
                    //单据金额
                    $totalMoney = self::sale_money('purchase_get_order', $array['sourceId']);
                    if (empty($targetInfo['id'])) {
                        //采购退货单
                        $orderType = '采购退货单';
                        $targetInfo = query('purchase_refund_order', "id = '$array[sourceId]'");
                        //单据金额
                        $totalMoney = self::sale_money('purchase_refund_order', $array['sourceId']);
                    }
                    if ($targetInfo['supplierId'] != $info['targetId']) {
                        //转过的单子
                        $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$targetInfo[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                    }
                    $totalMoney = $orderType == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                    //已核销金额
                    $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    //核销单
                    $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    if ($array['money'] > $totalMoney - $checkMoney) {
                        return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.compute.tips'));
                    } elseif ($array['money'] == $totalMoney - $checkMoney) {
                        $writeOffArray[] = ['sourceTable' => $array['sourceTable'], 'sourceId' => $array['sourceId'], 'isWriteOff' => 1];
                    }
                }

                break;
            case '预收冲应收':
                $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' and classify = '预收' order by list"));
                foreach ($all['array'] as $array) {
                    //收款单
                    $targetInfo = query('receipt', "id = '$array[sourceId]'");
                    //单据金额
                    $totalMoney = find(array('table' => 'receipt_detail', "single" => "orderId = '$targetInfo[id]'", 'sum' => "money"));
                    //已核销金额
                    $checkMoney = find(array('table' => "receipt_source", "single" => "orderId = '$targetInfo[id]'", 'sum' => "money"));
                    //核销单
                    $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    if ($array['money'] > $totalMoney - $checkMoney) {
                        return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.compute.tips'));
                    }
                }
                $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' and classify = '应收' order by list"));
                foreach ($all['array'] as $array) {
                    //销售发货单
                    $orderType = '销售发货单';
                    $targetInfo = query('sale_send_order', "id = '$array[sourceId]'");
                    //单据金额
                    $totalMoney = self::sale_money('sale_send_order', $array['sourceId']);
                    if (empty($targetInfo['id'])) {
                        //销售退货单
                        $orderType = '销售退货单';
                        $targetInfo = query('sale_refund_order', "id = '$array[sourceId]'");
                        //单据金额
                        $totalMoney = self::sale_money('sale_refund_order', $array['sourceId']);
                    }
                    if ($targetInfo['khid'] != $info['targetId']) {
                        //转过的单子
                        $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$targetInfo[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                    }
                    $totalMoney = $orderType == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                    //已核销金额
                    $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    //核销单
                    $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    if ($array['money'] > $totalMoney - $checkMoney) {
                        return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.compute.tips'));
                    } elseif ($array['money'] == $totalMoney - $checkMoney) {
                        $writeOffArray[] = ['sourceTable' => $array['sourceTable'], 'sourceId' => $array['sourceId'], 'isWriteOff' => 1];
                    }
                }
                break;
            case '应收冲应付':
                $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' and classify = '应收' order by list"));
                foreach ($all['array'] as $array) {
                    //销售发货单
                    $orderType = '销售发货单';
                    $targetInfo = query('sale_send_order', "id = '$array[sourceId]'");
                    //单据金额
                    $totalMoney = self::sale_money('sale_send_order', $array['sourceId']);
                    if (empty($targetInfo['id'])) {
                        //销售退货单
                        $orderType = '销售退货单';
                        $targetInfo = query('sale_refund_order', "id = '$array[sourceId]'");
                        //单据金额
                        $totalMoney = self::sale_money('sale_refund_order', $array['sourceId']);
                    }
                    if ($targetInfo['khid'] != $info['targetId']) {
                        //转过的单子
                        $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$targetInfo[id]' and targetIn = '$info[targetId]'", 'sum' => "money"));
                    }
                    $totalMoney = $orderType == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                    //已核销金额
                    $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    //核销单
                    $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    if ($array['money'] > $totalMoney - $checkMoney) {
                        return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.compute.tips'));
                    } elseif ($array['money'] == $totalMoney - $checkMoney) {
                        $writeOffArray[] = ['sourceTable' => $array['sourceTable'], 'sourceId' => $array['sourceId'], 'isWriteOff' => 1];
                    }
                }
                $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' and classify = '应付' order by list"));
                foreach ($all['array'] as $array) {
                    //采购收货单
                    $orderType = '采购收货单';
                    $targetInfo = query('purchase_get_order', "id = '$array[sourceId]'");
                    //单据金额
                    $totalMoney = self::sale_money('purchase_get_order', $array['sourceId']);
                    if (empty($targetInfo['id'])) {
                        //采购退货单
                        $orderType = '采购退货单';
                        $targetInfo = query('purchase_refund_order', "id = '$array[sourceId]'");
                        //单据金额
                        $totalMoney = self::sale_money('purchase_refund_order', $array['sourceId']);
                    }
                    if ($targetInfo['supplierId'] != $info['otherId']) {
                        //转过的单子
                        $totalMoney = find(array('table' => 'write_off_order_replace', "where" => "sourceId = '$targetInfo[id]' and targetIn = '$info[otherId]'", 'sum' => "money"));
                    }
                    $totalMoney = $orderType == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                    //已核销金额
                    $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    //核销单
                    $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    if ($array['money'] > $totalMoney - $checkMoney) {
                        return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.compute.tips'));
                    } elseif ($array['money'] == $totalMoney - $checkMoney) {
                        $writeOffArray[] = ['sourceTable' => $array['sourceTable'], 'sourceId' => $array['sourceId'], 'isWriteOff' => 1];
                    }
                }
                break;
            case '应收转应收':
                $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]'  order by list"));
                foreach ($all['array'] as $array) {
                    //销售发货单
                    $orderType = '销售发货单';
                    $targetInfo = query('sale_send_order', "id = '$array[sourceId]'");
                    //单据金额
                    $totalMoney = self::sale_money('sale_send_order', $array['sourceId']);
                    if (empty($targetInfo['id'])) {
                        //销售退货单
                        $orderType = '销售退货单';
                        $targetInfo = query('sale_refund_order', "id = '$array[sourceId]'");
                        //单据金额
                        $totalMoney = self::sale_money('sale_refund_order', $array['sourceId']);
                    }
                    $totalMoney = $orderType == '销售退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                    //已核销金额
                    $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    //核销单
                    $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    if ($array['money'] > $totalMoney - $checkMoney) {
                        return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.compute.tips'));
                    } elseif ($array['money'] == $totalMoney - $checkMoney) {
                        $writeOffArray[] = ['sourceTable' => $array['sourceTable'], 'sourceId' => $array['sourceId'], 'isWriteOff' => 1];
                    }
                }
                break;
            case '应付转应付':
                $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' order by list"));
                foreach ($all['array'] as $array) {
                    //采购收货单
                    $orderType = '采购收货单';
                    $targetInfo = query('purchase_get_order', "id = '$array[sourceId]'");
                    //单据金额
                    $totalMoney = self::sale_money('purchase_get_order', $array['sourceId']);
                    if (empty($targetInfo['id'])) {
                        //采购退货单
                        $orderType = '采购退货单';
                        $targetInfo = query('purchase_refund_order', "id = '$array[sourceId]'");
                        //单据金额
                        $totalMoney = self::sale_money('purchase_refund_order', $array['sourceId']);
                    }
                    $totalMoney = $orderType == '采购退货单' ? -round($totalMoney, 2) : round($totalMoney, 2);
                    //已核销金额
                    $checkMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    //核销单
                    $checkMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => "b.state = '已确认' and a.sourceId = '$targetInfo[id]'", 'sum' => "money"));
                    if ($array['money'] > $totalMoney - $checkMoney) {
                        return str_replace(['{{orderNo}}'], [$targetInfo['orderNo']], L('writeOffOrder.compute.tips'));
                    } elseif ($array['money'] == $totalMoney - $checkMoney) {
                        $writeOffArray[] = ['sourceTable' => $array['sourceTable'], 'sourceId' => $array['sourceId'], 'isWriteOff' => 1];
                    }
                }
                break;
        }
        return $writeOffArray;
    }

    /**
     * 确认
     */
    public function confirmEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        $res = $this->compute($info);//判断核销金额
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = L('writeOffOrder.confirmEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('writeOffOrder.confirmEdit.empty');
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = L('writeOffOrder.confirmEdit.stateError');
        } elseif (!is_array($res)) {
            $json['warn'] = $res;
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            switch ($info['type']) {
                case '预收冲应收':
                    $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' order by list"));
                    foreach ($all['array'] as $array) {
                        if ($array['classify'] =='应收'){
                            $bool = supplierClass::record_cl($info['targetId'], '-', -$array['money'], $info['recordDate'], self::table . '_detail', $array['id'], str_replace(['{{orderNo}}'], [$info['orderNo']], L('writeOffOrder.confirmEdit.recordTips')), '客户', $info['orderNo'], "核销单类型【预收冲应收】，应收核销，明细ID:{$array['id']}", classify: '核销');
                        }else{
                            $inReceipt = query($array['sourceTable'], "id = '$array[sourceId]'");
                            $bool = supplierClass::record_cl($info['targetId'], '-', $array['money'], $info['recordDate'], self::table . '_detail', $array['id'], "收款单【{$inReceipt['orderNo']}】在核销单中核销", '客户', $info['orderNo'], "收款单【{$inReceipt['orderNo']}】在核销单类型【预收冲应收】被核销核销，核销明细ID:{$array['id']}", classify: '核销');
                        }
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            break;
                        }
                    }
                    break;
                case '预付冲应付':
                    $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' order by list"));
                    foreach ($all['array'] as $array) {
                        if ($array['classify'] =='应付'){
                            $bool = supplierClass::record_cl($info['targetId'], '+', $array['money'], $info['recordDate'], self::table . '_detail', $array['id'], str_replace(['{{orderNo}}'], [$info['orderNo']], L('writeOffOrder.confirmEdit.recordTips')), '供应商', $info['orderNo'], "核销单类型【预付冲应付】，应付核销，明细ID:{$array['id']}", classify: '核销');
                        }else{
                            $payReceipt = query($array['sourceTable'], "id = '$array[sourceId]'");
                            $bool = supplierClass::record_cl($info['targetId'], '+', -$array['money'], $info['recordDate'], self::table . '_detail', $array['id'], "付款单【{$payReceipt['orderNo']}】在核销单中核销", '供应商', $info['orderNo'], "付款单【{$payReceipt['orderNo']}】在核销单类型【预收冲应收】被核销核销，核销明细ID:{$array['id']}", classify: '核销');
                        }
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            break;
                        }
                    }
                    break;
                case '应收冲应付':
                    $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]'  order by list"));
                    foreach ($all['array'] as $array) {
                        if ($array['classify'] == '应收') {
                            $bool = supplierClass::record_cl($info['targetId'], '-', -$array['money'], $info['recordDate'], self::table . '_detail', $array['id'], str_replace(['{{orderNo}}'], [$info['orderNo']], L('writeOffOrder.confirmEdit.recordTips')), '客户', $info['orderNo'], "核销单类型【应收冲应付】，应收核销，明细ID:{$array['id']}", classify: '核销');
                        } else {
                            $bool = supplierClass::record_cl($info['otherId'], '+', $array['money'], $info['recordDate'], self::table . '_detail', $array['id'], str_replace(['{{orderNo}}'], [$info['orderNo']], L('writeOffOrder.confirmEdit.recordTips')), '供应商', $info['orderNo'], "核销单类型【应收冲应付】，应付核销，明细ID:{$array['id']}", classify: '核销');
                        }
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            break;
                        }
                    }
                    break;
                case '应收转应收':
                    $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' order by list"));
                    foreach ($all['array'] as $array) {
                        $bool = supplierClass::record_cl($info['targetId'], '-', -$array['money'], $info['recordDate'], self::table . '_detail', $array['id'], str_replace(['{{orderNo}}'], [$info['orderNo']], L('writeOffOrder.confirmEdit.recordTips')), '客户', $info['orderNo'], "核销单类型【应收转应收】，转出客户，明细ID:{$array['id']}", classify: '核销');
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            break;
                        }
                        $bool = supplierClass::record_cl($info['otherId'], '+', $array['money'], $info['recordDate'], self::table . '_detail', $array['id'], str_replace(['{{orderNo}}'], [$info['orderNo']], L('writeOffOrder.confirmEdit.recordTips')), '客户', $info['orderNo'], "核销单类型【应收转应收】，转入客户，明细ID:{$array['id']}", classify: '核销');
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            break;
                        }
                    }
                    break;
                case '应付转应付':
                    $all = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]' order by list"));
                    foreach ($all['array'] as $array) {
                        $bool = supplierClass::record_cl($info['targetId'], '+', $array['money'], $info['recordDate'], self::table . '_detail', $array['id'], str_replace(['{{orderNo}}'], [$info['orderNo']], L('writeOffOrder.confirmEdit.recordTips')), '供应商', $info['orderNo'], "核销单类型【应付转应付】，转出供应商，明细ID:{$array['id']}", classify: '核销');
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            break;
                        }
                        $bool = supplierClass::record_cl($info['otherId'], '-', -$array['money'], $info['recordDate'], self::table . '_detail', $array['id'], str_replace(['{{orderNo}}'], [$info['orderNo']], L('writeOffOrder.confirmEdit.recordTips')), '供应商', $info['orderNo'], "核销单类型【应付转应付】，转入供应商，明细ID:{$array['id']}", classify: '核销');
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            break;
                        }
                    }
                    break;
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                $this->commitTrans();
                //修改源单核销状态
                foreach ($res as $val) {
                    update(array(
                        "table" => $val['sourceTable'],
                        "field" => ['isWriteOff' => $val['isWriteOff']],
                        "where" => "id = '$val[sourceId]'",
                    ));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('writeOffOrder.confirmEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            'targetId' => L('writeOffOrder.edit.kehu'),
            'type' => L('writeOffOrder.edit.type'),
            'recordDate' => L('writeOffOrder.edit.recordDate'),
        ];
        $rules = [
            'targetId' => 'required',
            'type' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        if ($info['type'] == '应收转应收' && empty($info['otherId'])) {
            return L('writeOffOrder.editEdit.choiceClient');
        }
        if ($info['type'] == '应收转应收' && $info['targetId'] == $info['otherId']) {
            return L('writeOffOrder.editEdit.sameClient');
        }
        if ($info['type'] == '应付转应付' && empty($info['otherId'])) {
            return L('writeOffOrder.editEdit.choiceSupplier');
        }
        if ($info['type'] == '应付转应付' && $info['targetId'] == $info['otherId']) {
            return L('writeOffOrder.editEdit.sameSupplier');
        }
        switch ($info['type']) {
            case '预收冲应收':
                $mxMoneyArr = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '预收'", 'sum' => "money"));
                $checkMoneyArr = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收'", 'sum' => "money"));
                break;
            case '预付冲应付':
                $mxMoneyArr = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '预付'", 'sum' => "money"));
                $checkMoneyArr = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付'", 'sum' => "money"));
                break;
            case '应收冲应付':
                $mxMoneyArr = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应付'", 'sum' => "money"));
                $checkMoneyArr = find(array('table' => self::table . "_detail", 'where' => "orderId = '$info[id]' and classify = '应收'", 'sum' => "money"));
                break;
            default:
                $mxMoneyArr = 0;
                $checkMoneyArr = 0;
                break;
        }
        if (in_array($info['type'], ['预收冲应收', '预付冲应付', '应收冲应付']) && round($mxMoneyArr, 2) != round($checkMoneyArr, 2)) {
            return L('writeOffOrder.editEdit.moneyAtypism');
        }
        $result = find(array('table' => self::table . "_detail", 'field' => 'id,sourceId,money', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善核销明细";
        }
        if(static::is_null_array(array_column($result['array'],'sourceId'))){
            return "核销明细【源单】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'money'),false)){
            return "核销明细【核销金额】不能为空，且必须大于0";
        }

        return true;
    }
    /**
     * 提交
     */
    public function commitEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('writeOffOrder.commitEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('writeOffOrder.commitEdit.empty');
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = L('writeOffOrder.commitEdit.stateError');
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('writeOffOrder.commitEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = L('writeOffOrder.operate.sure');
                $title = L('writeOffOrder.operate.sureTitle');
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = L('writeOffOrder.operate.edit');
                $title = L('writeOffOrder.operate.editTitle');
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = L('writeOffOrder.operate.cancel');
                $title = L('writeOffOrder.operate.cancelTitle');
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = L('writeOffOrder.operate.del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('writeOffOrder.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('writeOffOrder.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('writeOffOrder.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = L('writeOffOrder.delete.fail');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table . "_detail", "where" => " orderId = '$id' "));
                    delete(array("table" => self::table."_replace", "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('writeOffOrder.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('writeOffOrder.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('writeOffOrder.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('writeOffOrder.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}
